简体   繁体   English

C ++:setw()仅在循环中的第一行上工作

[英]C++: setw() only working on first row, in loop

I am trying to parse through a text file and have it output the contents onto the console with formatting by using setw(). 我试图解析文本文件,并使用setw()将内容输出到控制台格式化。 My problem is that only the first row is formatted correctly, with the rest defaulting back to the left. 我的问题是只有第一行格式正确,其余的默认返回到左侧。

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;


}

My goal is to get the output to align to the longest word (which is 20 spaces in length) on the right, but my output is ending up like this: 我的目标是让输出与右边最长的单词(长度为20个空格)对齐,但我的输出结果如下:

           WordThatAlignsRight
notAligning
my longest sentence goal align
notAligning

I am wanting each sentence to right align 20 spaces throughout the loop. 我希望每个句子在整个循环中对齐20个空格。 Any help is appreciated, thanks! 任何帮助表示赞赏,谢谢!

std::setw only works on the next element, after that there is no effect. std::setw只适用于下一个元素,之后没有效果。 For further information pls follow this link. 有关详细信息,请点击此链接。 .

The code on the linked site will show you very clearly how std::setw works. 链接网站上的代码将非常清楚地向您展示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";
}

Output: 输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM