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

标签 c++ iomanip setw

我正在尝试解析一个文本文件,并使用 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 个空格。感谢任何帮助,谢谢!

最佳答案

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"

关于C++:setw()仅在循环中的第一行上工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55274581/

相关文章:

C++ 如何格式化包含可变整数的文本行,使其在给定宽度内右对齐?

C++ setw 不对齐列

c# - 为什么 C# 泛型的设计行为与 C++ 模板如此不同?

c++ - 在 Windows 上跟踪移动到回收站的进度

c++ - 使用 iomanip 自动间距

c++ - 如何使我的函数对重载的 iostream 提取运算符具有粘性

c++ - 如何在保持显示位数的同时向左移动小数点?

c++ - 初学者 C++ - 带有奇怪 setw 错误的简单随机游走程序

c++ - CLOCKS_PER_SEC, token 前缺少二元运算符... [NFIQ 2.0]

c++ - 在传递的对象将要被销毁之前,发出传递 QObject 指针作为参数的信号是否安全?