我正在尝试解析一个文本文件,并使用 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/