如何正确打印带边距的长字符串(setw())?

时间:2016-06-03 18:53:06

标签: c++ iomanip

我的字符串是嗯,350个字符长。我需要将它放在控制台中心,因此左右两侧的边距相同。

当我尝试setw()时,我得到一个像这样的输出(只有开头有边距)。

          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

我想要实现的目标:

             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

我的代码看起来像这样(仅针对左侧,我甚至没有尝试第二个):

out << left << setw(20) << " " << longString << endl;

如果有人知道如何实现我的目标,我将不胜感激!

1 个答案:

答案 0 :(得分:0)

如果您知道线宽,则相当简单:

#include <iostream>
#include <string>
#include <iomanip>

int main(){
    std::string longstring = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
    int margin = 5;
    int linewidth = 10;
    int pos = 0;
    while (pos < longstring.size()){
        std::cout << std::setw(linewidth) 
                  << longstring.substr(pos,linewidth-margin) << std::endl;
        pos+= linewidth-margin;
    }
}