How to properly align text ?

Hi, my text gets distorted as soon as any variable gets 2 numbers in it. How can I make my text stay in the same position ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
using namespace std;
int main()
{
    int x, y1, y2;
    for(x=0;x<=10;x++) {
        y1 = 2*x+2;
        y2 = 3*x+1;
        cout << x << " " << y1 << " " << y2 << " ";
        if(y1==y2) cout << "Equals" << endl;
        else cout << "***" << endl;
    }
}
No idea if you can somehow do it with cout in an easy way but you could use printf().

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//ripped of from http://www.cplusplus.com/reference/cstdio/printf/
#include <stdio.h>

int main()
{
   printf ("foo: %5d \n", 1);
   printf ("foo: %5d \n", 12);
   printf ("foo: %5d \n", 123);
   printf ("foo: %5d \n", 1234);
   printf ("foo: %5d bar: %7d", 1234, 5678);

   return 0;
}


With the number after the % you can determine the width of the space where your numbers are inserted.
Last edited on
@Arquon

Use the iomanip library or use the stdio.h library (from C language) and use printf() function.
Last edited on
No reason to mix C (printf) and C++.

See setw().
http://www.cplusplus.com/reference/iomanip/setw/

Last edited on
I tried using setw, but the last line still gets distorted. Am I doing something wrong ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
    int x, y1, y2;
    for(x=0;x<=10;x++) {
        y1 = 2*x+2;
        y2 = 3*x+1;
        cout << x << " " << setw(4) << y1 << " " << setw(4) << y2 << " ";
        if(y1==y2) cout << setw(4) << "Equals" << endl;
        else cout << setw(4) << "***" << endl;
    }
}
line 10: The first field you're outputting is x. You have no setw() for x, so x defaults to the number of columns needed.

It worked, thank you ! It looks so beautiful to my eye right now.
Topic archived. No new replies allowed.