setw 流操作器(空间计数)是如何工作的?例如,当有一个\t时,我想打印带有四个空格的a,所以我使用\t,并将\t与setw进行比较。
我写的代码:
# include <iostream>
# include <iomanip>
int main()
{
std::cout<<"\t"<<"a\n";
std::cout<<std::setw(9)<<"a\n";
return 0;
}输出
a // This is 1 '\t'
a // This is setw()所以我认为是:
setw(18) = \t\t
密码起作用了。但是当我删除\n的时候,它并没有变成一条直线。
# include <iostream>
# include <iomanip>
int main()
{
std::cout<<"\t\t"<<"a\n";
std::cout<<std::setw(18)<<"a";
return 0;
}它给了我这个输出:
a
a怎么了?
发布于 2022-07-02 08:49:22
这是因为您需要在\n上添加setw(18)。setw**.** ,这适用于任何
样本代码:
# include <iostream>
# include <iomanip>
int main()
{
std::cout<<"\t\t"<<"a\n";
std::cout<<std::setw(18)<<"a\n"; // And you add the \n here
return 0;
}输出:
a
a另一个解决办法是:
# include <iostream>
# include <iomanip>
int main()
{
std::cout<<"\t\t"<<"a\n";
std::cout<<std::setw(18)<<"a "; // And you add the a space here
return 0;
}输出将是相同的。。
我们应该放置\n或空格的原因是:
这是因为它证明了整个双字符字符串
"a"\n的正确性,而不仅仅是a.如果单独打印换行符(. << 'a‘<< '\n'),则会得到相同的“错误”。您也可以通过使用几乎任何空格字符(如. << "a“)来解决这个问题;您可能希望在同一程序中使用带有或不带换行符的打印来查看差异。
https://stackoverflow.com/questions/72837730
复制相似问题