简体   繁体   中英

Align a string with dashes in std::stringstream

I am trying to write a set of number into a stringstream looking like this:

SOME_TEXT    12-23-43    SOME_OTHER_TEXT

12-23-43 are three numbers divided by dash ('-'), numbers can be 1 or 2-digits (like 1-2-3 or 12-1-47 so the length of the whole set differs). The whole set should be aligned to the left and take exactly 12 characters including spaces. When I try to apply std::left manipulator it works only for the first number. How can I do it?

Here is an example using another ostringstream :

#include <iostream>
#include <sstream>
#include <iomanip>

int main()
{
  std::ostringstream oss1;
  oss1 << 5 << "-" << 31 << "-" << 6;
  std::ostringstream oss;
  oss << "SOME_TEXT    " << std::setw(12) << std::left << oss1.str() << "SOME_OTHER_TEXT";
  std::cout << oss.str() << std::endl;
  return 0;
}

Got it working with sprintf, I'm surprised though it can't be done with stringstream:

char buffer[12];
sprintf(buffer, "%d-%d-%d", n1, n2, n3);            
output << std::setw(12) << std::left << buffer;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM