Don't print space after last number [duplicate]
LANGUAGE: C++ Hello, in the following function (code block) i have written a line to print an space between characters but i don't want print spaces after last characters. How can i solve this problem?
bool perfecto(int n)
{
int suma, i;
suma = 0;
for (i = 1; i < n; i++)
{
if (n % i == 0)
{
suma += i;
cout << i << " ";
}
}
if (suma == n)
return true;
else
return false;
}
Best regards. Ángel Manuel.
The simplest way would be to turn the problem around: if you only print spaces before printing the number (and not after) then it becomes how not to print the first time, which is much easier.
I'll let you figure it out :)
bool perfecto(int n)
{
int suma, i;
suma = 0;
bool first = true;
for (i = 1; i < n; i++)
{
if (n % i == 0)
{
suma += i;
if ( !first )
{
cout << " ";
}
cout << i;
first = false;
}
}
if (suma == n)
return true;
else
return false;
}
You can either check if i is equal to n - 1 and not print it in that case, or something like
std::cout << "1";
for (int i = 2; i < n; ++i)
{
std::cout << " " << i;
}
In the second case, you have to watch for for a case where n is 1 or less
There are a variety of options. In this case, probably the easiest is to print spaces BEFORE elements except the first and use a flag to track the first element:
bool perfecto(int n)
{
int suma, i;
suma = 0;
bool first = true;
for (i = 1; i < n; i++)
{
if (n % i == 0)
{
suma += i;
if(!first)
{
std::cout << " ";
}
else first = false;
cout << i;
}
}
if (suma == n)
return true;
else
return false;
}
EDIT: Other popular alternatives are printing the first item and no delimiter outside the loop completely and then inside the loop you can always pre-print the item with no if-check at all. This approach wouldn't work as well with your loop though since you don't always know when the first item will print. You can also create wrapper ostream
like classes that keep track of their internal printing state and know when to put the spaces.
Replace this line: cout << i << " ";
with:
cout << i;
if (i == n-1)
cout << endl;
else
cout << " ";
精彩评论