# quick c++ question

**URL:** <https://boards.straightdope.com/t/quick-c-question/325465>\
**Category:** Factual Questions\
**Created:** [October 10, 2005, 12:18am UTC](https://boards.straightdope.com/t/quick-c-question/325465 "2005-10-10T00:18:28Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![remisser](https://avatars.discourse-cdn.com/v4/letter/r/b3f665/32.png) [@remisser](https://boards.straightdope.com/u/remisser)\
**Post date:** [October 10, 2005, 12:18am UTC](https://boards.straightdope.com/t/quick-c-question/325465/1 "2005-10-10T00:18:28Z")

</div>

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?

---

<div class="post-metadata">

**Author:** ![ultrafilter](https://avatars.discourse-cdn.com/v4/letter/u/3d9bf3/32.png) [@ultrafilter](https://boards.straightdope.com/u/ultrafilter)\
**Post date:** [October 10, 2005, 1:48am UTC](https://boards.straightdope.com/t/quick-c-question/325465/2 "2005-10-10T01:48:46Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![Omphaloskeptic](https://avatars.discourse-cdn.com/v4/letter/o/bcef8e/32.png) [@Omphaloskeptic](https://boards.straightdope.com/u/Omphaloskeptic)\
**Post date:** [October 10, 2005, 8:14pm UTC](https://boards.straightdope.com/t/quick-c-question/325465/3 "2005-10-10T20:14:59Z")

</div>

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:

```auto

  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 🙂 :

```auto

  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.
