tags:

views:

43

answers:

3

After getting a helpful answer here, I have run into yet another problem: displaying two or more strings in the column I want it to be displayed in. For an example of the problem I have, I want this output:

Come here! where?             not here!

but instead get

Come here!                     where? not here!

when I use the code

cout << left << setw(30) << "Come here!" << " where? " << setw(20) << "not here!" << endl;

I made sure (I think) that the width of both columns could contain the two strings, but no matter how large I set the width of the columns to be, the error is still there.

+2  A: 

You should print the contents of each column as a single string, instead of multiple consecutive strings, because setw() only formats the next string to be printed. So you should concatenate the strings before printing, using e.g. string::append() or +:

cout << left << setw(30) << (string("Come here!") + " where? ") << setw(20) << "not here!" << endl;
Péter Török
+1  A: 

setw only covers the next string, so you'll need to concatenate them.

cout << left << setw(30) << (string("Come here!") + string(" where? ")) << setw(20) << "not here!" << endl;
Peter Alexander
Um, `(string("Come here!") + " where? ")` would be enough and safes one `std::string` ctor. (Not that it matters, when we could write `"Come here! where? "`, but, hey, I'm pedantic...)
sbi
Yeah, it saves typing, but IMO it breaks symmetry and makes it less readable.
Peter Alexander
@Poita_: It's not that it saves typing, it saves one _call_ to a ctor, thus, run-time.
sbi
+1  A: 

As stated, setw() only applies to the next input, and you are trying to apply it to two inputs.

An alternative to the other suggestions which gives you a chance to use variables in place of literal constants:

#include <iostream>
#include <sstream>
#include <iomanip>
using namespace std;

int main()
{
    stringstream ss;
    ss << "Come here!" << " where?";
    cout << left << setw(30) << ss.str() << setw(20) << "not here!" << endl;
    return 0;
}
John Dibling