setw(); HELP.

closed account (ivDwAqkS)
how do I make the output of the " | " outs in one vertical line, as you can see, it prints something like this...

5 |9130
5.2 |11130.1
5.4 |13465.4
...
6 |22902
1
2
//its suppose that has 5 space of 
//width because of the setw(5) but it doesn't 
why?
6.2 |27013.5



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <iomanip>
using namespace std;

double p5(double);
double p3(double);

int main(){
    double x;


    for(x = 5; x <= 10; x+=0.2){
        double y = 3*p5(x) - 2*p3(x) + x;
        if(x == 5 || x == 6 || x == 7 || x == 8 || x ==9 || x == 10)//doesn't obey why?
            cout << " " << x << setw(5) << "|" << y << " " << endl;
        else
            cout << " " << x << setw(3) << "|" << y << " " << endl;
    }

    return 0;
}

double p3(double n){
    return n*n*n;
}
double p5(double n){
    return n*n*n*n*n;
}
Last edited on
closed account (ivDwAqkS)
can someone tell me why it happens? and how to use it correctly?
You don't really need the if there. Consider these options:
1
2
3
4
5
6
7
for (x = 5; x <= 10; x += 0.2){
    double y = 3 * p5(x) - 2 * p3(x) + x;
    cout << " " << setw(3) << x << " | " << y << " " << endl;          
}
   5 | 9130
 5.2 | 11130.1
 5.4 | 13465.4
 5.6 | 16176.3
 5.8 | 19306.3
   6 | 22902
 6.2 | 27013.5

1
2
3
4
5
6
7
for (x = 5; x <= 10; x += 0.2){
    double y = 3 * p5(x) - 2 * p3(x) + x;
    cout << " " << setw(3) << x << " |" << setw(8) << y << " " << endl;
}
   5 |    9130
 5.2 | 11130.1
 5.4 | 13465.4
 5.6 | 16176.3
 5.8 | 19306.3
   6 |   22902
 6.2 | 27013.5

1
2
3
4
5
6
7
for (x = 5; x <= 10; x += 0.2){
    double y = 3 * p5(x) - 2 * p3(x) + x;
    cout << " "<< x << "\t| " << y << " " << endl;                     
}
 5      | 9130
 5.2    | 11130.1
 5.4    | 13465.4
 5.6    | 16176.3
 5.8    | 19306.3
 6      | 22902
 6.2    | 27013.5
closed account (ivDwAqkS)
thank you so much, I need to learn more about iomanip functions and how to use them can you give me some good tutorials with good examples?
I don't know about tutorials on iomanipulators, but this start here:
http://www.cplusplus.com/reference/iomanip/
Topic archived. No new replies allowed.