C ++:在打印出字符串后设置填充

C++: set fill after printing out a string

我正在尝试 cout 一个字符串,以便输出的总长度为 15。

比如字符串是"Tom",那么我想要cout之后的12space秒。我知道如何使用 setfillsetw 来获得领先的 spaces,但是之后是否有内置的填充 spaces 的方式?或者唯一的方法是获取字符串长度并在字符串末尾附加一串 space?

谢谢!

使用在headerios中定义的IO操纵器std::left

http://en.cppreference.com/w/cpp/io/manip/left

我认为您正在寻找 std::left 输出修饰符。

#include <iomanip>    // std::setw
#include <ios>        // std::left
#include <iostream>   // std::cout
#include <string>     // std::string

int
main()
{
  const std::string words[] = {
    "Tom",
    "Ferdinand",
    "And finally some longer string",
  };
  for (const auto& w : words)
    std::cout << std::setw(12) << std::left << w << "|\n";
}

输出:

Tom         |
Ferdinand   |
And finally some longer string|

I'm trying to cout a string so that the total length of the output is, say 15. For example, if the string is "Tom", then I want 12 spaces after cout.

我用过以下...

// ...
{
    std::stringstream ss1;
    ss1 << "Tom"; // insert 
    const int NameFieldSize = 15;
    while (ss1.str().size() < NameFieldSize) ss << " ";
    // ... insert the rest of the info to ss1
    // now write the full string to cout (or file)
    std::cout << ss1.str() << std::endl;
}
// ...

stringstream 的工作方式与 cout 一样,所有格式控制,但因为它是基于 ram 的,所以速度要快得多。

请注意,当 ss1 已经长于 NameFieldSize 时,代码和检测然后可能 'fix' 输出格式。