简体   繁体   English

将字符串与std :: stringstream中的破折号对齐

[英]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). 12-23-43是用破折号('-')分隔的三个数字,数字可以是1或2位数字(例如1-2-3或12-1-47,因此整个长度不同)。 The whole set should be aligned to the left and take exactly 12 characters including spaces. 整个集合应该向左对齐,并且正好包含空格在内的12个字符。 When I try to apply std::left manipulator it works only for the first number. 当我尝试应用std :: left操纵器时,它仅适用于第一个数字。 How can I do it? 我该怎么做?

Here is an example using another ostringstream : 这是使用另一个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: 与sprintf一起使用时,我很惊讶,尽管使用stringstream无法完成它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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