std::setw 如何处理字符串输出?

How does std::setw work with string output?

我正在尝试使用 set width setw 将字符串输出到输出文件,但是,我无法使其工作。我有以下示例。

// setw example
#include <iostream>     
#include <iomanip>      
#include <fstream>

int main () {
    std::ofstream output_file;
    output_file.open("file.txt");
    output_file << "first" <<std::setw(5)<< "second"<< std::endl;
    output_file.close();
  return 0;
}

编辑: 对于上面的行,我希望 firstsecond 之间有很多空格,比如 first second

我几乎看不到任何空格,输出就像 firstsecond 我想我错过了 setw()

的工作

注意:对于整数,它工作正常只是:

output_file << 1 <<std::setw(5)<< 2 << std::endl;

我哪里做错了??

我怀疑您对 std::setw 的理解根本不正确。我认为您需要更多类似以下内容的组合:

您的代码中发生了什么:

  • 使用 std::setw(5) 建立五个字符的字段宽度。
  • 发送"first"到流中,长度为五个字符,所以建立的字段宽度被完全消耗。没有额外的填充发生。
  • "second" 发送到长度为六个字符的流,因此再次消耗整个字段宽度(并且 in-fact 被破坏)。同样,没有填充发生

如果您打算拥有这样的东西(上面的列号显示位置):

 col: 0123456789012345678901234567890123456789
      first     second    third     fourth

注意每个单词是如何从 10 的偶数倍开始的。一种方法是使用 :

  • 一个输出位置std::left(所以填充,如果有的话在右边达到所需的宽度)。这是字符串的默认设置,但确定无妨。
  • 一个std::setfill(' ')的填充字符。同样,默认值。
  • 一个字段的宽度std::setw(10)为什么这么大?见下文

例子

#include <iostream>
#include <iomanip>

int main ()
{
    std::cout << std::left << std::setfill(' ')
              << std::setw(10) << "first"
              << std::setw(10) << "second"
              << std::setw(10) << "third"
              << std::setw(10) << "fourth" << '\n';
    return 0;
}

输出(添加了列号)

0123456789012345678901234567890123456789
first     second    third     fourth

那么如果我们将输出位置更改为 std::right 会发生什么?那么,使用相同的程序,仅将第一行更改为:

std::cout << std::right << std::setfill(' ')

我们得到

0123456789012345678901234567890123456789
     first    second     third    fourth

最后,一种查看填充字符应用位置的建设性方法是将填充字符简单地更改为可见的内容(即 space 之外的内容)。最后两个示例输出,将填充字符更改为 std::setfill('*') 会产生以下输出:

第一个

first*****second****third*****fourth****

第二

*****first****second*****third****fourth    

请注意,在这两种情况下,由于 none 个单独的输出项违反了 std::setw 值,因此每个的 输出行大小是相同的.所有改变的是应用填充的位置和输出在 std::setw 规范内对齐。