quick c++ question

basically i’m trying to make 2 variables output to each other left justified with only a space between them…

cout << setw(20) << fname1 lname1

I don’t know what goes between fname1 and lname1 to make that work. But i basically want lname1 to left justify to fname1 with a space between and be within the confines of the 20 space width.

Can anyone help me out?

What if lname1, fname1, or the concatenation of the two is longer than 20 characters?

cout << setw(20) << fname1 << ’ ’ << lname1 << flush; should do something reasonably close to what you want to do, I think. I usually use stdio instead of streams, so I’m not 100% sure.

C++ streams are somewhat unwieldy for formatted output; I prefer the C *printf functions. If you insist on C++ streams, though, here’s one way:


  ostringstream os;
  os << fname1 << " " << lname1;

  cout << setw(20) << left << os.str();

This will left-justify the concatenation of fname1 and lname1 (with one space separating the two) in a 20-character field, expanding if necessary. (The setw() affects only the next value to produce output. The left sets left justification (standard is right). For these you may need to #include .)

A C solution, which I think is legal :slight_smile: :


  printf( "%-*s", 20-printf( "%s ", fname1 ), lname1 );

ultrafilter’s solution will set fname1 right-justified in a 20-character field, with lname1 following it and not justified.