Formatting using ostringstream

I am not sure how to get the "****" to always line up at the end of the error messages. These error messages occur when the user enters an invalid number out of the range specified. userChoice is the variable that holds the user's input.

1
2
3
4
5
6
7
8
9
ostringstream oss;
oss  << userChoice;

cout << left;
cout << "\n**** The number " << userChoice <<    setw(23+oss.str().size()) 
     << " is an invalid entry ";
cout << "****";
cout << setw(42+oss.str().size()) << "\n**** Please input a number between 0 and 7 ";
cout << "****\n\n\n";


If I enter a two digit number it aligns correctly.


Enter a command: 12

**** The number 12 is an invalid entry       ****
**** Please input a number between 0 and 7   ****


When i enter a 3 digit number it is off by 1 and when i enter a 4 digit number it is off by 2 and so on. I do not understand why this is happening.


Enter a command: 122

**** The number 122 is an invalid entry        ****
**** Please input a number between 0 and 7    ****
Last edited on
std::setw specifies the width of the next output so the trick is to make sure you output the whole sentence in one operation.

1
2
3
4
5
ostringstream oss;
cout << left;
oss << "\n**** The number " << userChoice << " is an invalid entry";
cout << setw(45) << oss.str() << "****";
cout << setw(45) << "\n**** Please input a number between 0 and 7" << "****\n\n\n";
Last edited on
Wow, that worked great! thank you very much. I dont think I would have ever noticed that.
Topic archived. No new replies allowed.