std :: setw如何使用字符串输出?

Awa*_*One 2 c++ string setw

我试图将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;
}
Run Code Online (Sandbox Code Playgroud)

编辑: 对于上述行我预计将有很多空间之间firstsecond,像 first second

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

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

output_file << 1 <<std::setw(5)<< 2 << std::endl;
Run Code Online (Sandbox Code Playgroud)

我做错了什么?

Who*_*aig 6

我怀疑你的理解std::setw是不正确的.我认为你需要更多的东西:

您的代码中发生了什么:

  • 用于std::setw(5)建立五个字符的字段宽度.
  • 发送"first"到流,长度为五个字符,因此已建立的字段宽度已完全消耗.不会发生额外的填充.
  • 发送"second"到流,这是六个字符长,所以再次,整个字段宽度被消耗(实际上已被破坏).同样,不会发生填充

如果您打算这样做(上面的列号显示位置):

 col: 0123456789012345678901234567890123456789
      first     second    third     fourth
Run Code Online (Sandbox Code Playgroud)

注意每个单词如何在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;
}
Run Code Online (Sandbox Code Playgroud)

输出(添加列数)

0123456789012345678901234567890123456789
first     second    third     fourth
Run Code Online (Sandbox Code Playgroud)

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

std::cout << std::right << std::setfill(' ')
Run Code Online (Sandbox Code Playgroud)

我们得到

0123456789012345678901234567890123456789
     first    second     third    fourth
Run Code Online (Sandbox Code Playgroud)

最后,通过简单地将填充字符更改为可见的东西(即除了空格之外的东西),可以看到填充字符的应用位置的一种建设性方法.最后两个示例输出,更改fill char以std::setfill('*')生成以下输出:

第一

first*****second****third*****fourth****
Run Code Online (Sandbox Code Playgroud)

第二

*****first****second*****third****fourth    
Run Code Online (Sandbox Code Playgroud)

请注意,在这两种情况下,由于没有单个输出项违反该std::setw值,因此每个输出项的输出行大小相同.所有改变的地方都是应用填充并且输出在std::setw规范内对齐.