【问题标题】:C++: setw() only working on first row, in loopC++:setw() 只在第一行工作,在循环中
【发布时间】:2019-08-11 23:06:11
【问题描述】:

我正在尝试解析一个文本文件,并让它通过使用 setw() 将内容输出到控制台并进行格式化。我的问题是只有第一行的格式正确,其余的默认回到左边。

while (test) 
{
    cout << setw(20) << right;
    string menu;
    price = 0;

    getline(test, menu, ',');
    test >> price;

    cout << setw(20) << right << menu;;

    if (price)
        cout << right << setw(10) << price;


}

我的目标是让输出与右侧最长的单词(长度为 20 个空格)对齐,但我的输出结果如下:

           WordThatAlignsRight
notAligning
my longest sentence goal align
notAligning

我希望每个句子在整个循环中右对齐 20 个空格。任何帮助表示赞赏,谢谢!

【问题讨论】:

    标签: c++ iomanip setw


    【解决方案1】:

    std::setw 只作用于下一个元素,之后就没有效果了。如需更多信息,请关注link.

    链接网站上的代码将非常清楚地向您展示std::setw 的工作原理。

    #include <sstream>
    #include <iostream>
    #include <iomanip>
    
    int main()
    {
        std::cout << "no setw:" << 42 << '\n'
                  << "setw(6):" << std::setw(6) << 42 << '\n'
                  << "setw(6), several elements: " << 89 << std::setw(6) << 12 << 34 << '\n';
        std::istringstream is("hello, world");
        char arr[10];
        is >> std::setw(6) >> arr;
        std::cout << "Input from \"" << is.str() << "\" with setw(6) gave \""
                  << arr << "\"\n";
    }
    

    输出:

    no setw:42
    setw(6):    42
    setw(6), several elements: 89    1234
    Input from "hello, world" with setw(6) gave "hello"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-04
      • 2017-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-24
      相关资源
      最近更新 更多