Reputation: 52911
I have the following program that generates a multiplication table. A formatting problem arises when the outputs reach the double digits. How do I straighten out the columns?
#include <iostream>
using namespace std ;
int main()
{
while (1 != 2)
{
int column, row, c, r, co, ro;
cout << endl ;
cout << "Enter the number of columns: " ;
cin >> column ;
cout << endl ;
cout << "Enter the number of rows: " ;
cin >> row ;
cout << endl ;
int temp[column] ;
c = 1 ;
r = 1 ;
for(ro = 1; ro < row ; ro ++ ){
for(co = 1; co < column ; co ++ ){
c = c ++ ;
r = r ++ ;
temp [c]= co * ro;
cout << temp[c] << " ";
}
cout << endl ;
}
system("pause");
}
}
Upvotes: 0
Views: 622
Reputation: 881273
C++ had setw
and setfill
for just this purpose. setw
sets the width and setfill
sets the fill character.
In your case, you can just use something like:
#include <iostream>
#include <iomanip>
int main (void) {
std::cout << std::setw(5) << 7 << std::endl; // will output " 7".
return 0;
}
You have a number of other problems with that code, at least some of which are listed below:
column*row
(or use a two-dimensional array).c = c++
is not a good idea, c++
will be enough to increment c
.c
twice in each iteration, once if the for
statement itself and once in the for
body.system("pause");
is an ugly hack where the language provides a perfectly good getchar
or cin
equivalent.while (1 != 2)
just looks plain wrong :-) since 1
will never equal 2
. Just use while (1)
or for(;;)
- any coder worth their salt will know what you mean.Upvotes: 3
Reputation: 308121
This is one of those situations where the old-fashioned printf
is a lot easier than cout
. Replace cout << temp[c] << " "
with printf("%2d ", temp[c])
.
And I hope you've discovered the bug in your c
calculation.
Upvotes: 2
Reputation: 1274
You can set width of your column elements by using stream manipulators like this:
cout << setw(3) << temp[c]
But this is something you need to fix besides: c = c++;
does not increment the variable!
Upvotes: 2
Reputation: 12824
use the setw output manipulator:
cout << setw(3) << temp[c];
By default, this uses spaces to fill, which it looks like you want.
You will need to include iomanip as the documentation says.
Upvotes: 2