[英]How does the setw stream manipulator work?
我想知道, setw
流操縱器(空間計數)如何工作? 例如,當有 1 個\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
聽起來合乎邏輯吧? 但是當我嘗試這段代碼時:
# include <iostream>
# include <iomanip>
int main()
{
std::cout<<"\t\t"<<"a\n";
std::cout<<std::setw(18)<<"a";
return 0;
}
它給了我這個輸出:
a
a
怎么了?
那是因為您需要在setw(18)
添加一個\n
。 這適用於任何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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.