我一直在从教科书中学习 C++,在我看来,他们对 setw() 函数用途的解释很差。简单地说,我不明白这些功能的用途,网上的解释也没有太大帮助。我读过它“设置要在输出操作中使用的字段宽度”或“将流的宽度参数设置为输出或输入精确为 n”,但这到底是什么意思?在你回答这个问题之前,我有两个代码,A 和 B,它们更能说明我的困惑。
代码 A:(来自教科书的示例代码):
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
string label;
double price;
cout << "\nPlease enter an article label: ";
cin >> setw(16);
cin >> label;
cin.sync();
cin.clear();
cout << "\nEnter the price of the article: ";
cin >> price;
cout << fixed << setprecision(2)
<< "\nArticle:"
<< "\n Label: " << label
<< "\n Price: " << price << endl;
return 0;
}
示例输入: 请输入文章标签:电脑输入文章价格:75
输出:
文章: 标签: 电脑 价格: 75.00
代码 B:(与 A 几乎完全相同的代码,但其中的三行被注释掉了)
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
string label;
double price;
cout << "\nPlease enter an article label: ";
//cin >> setw(16);
cin >> label;
//cin.sync();
//cin.clear();
cout << "\nEnter the price of the article: ";
cin >> price;
cout << fixed << setprecision(2)
<< "\nArticle:"
<< "\n Label: " << label
<< "\n Price: " << price << endl;
return 0;
}
示例输入: 请输入文章标签:电脑输入文章价格:75
输出:文章:标签:电脑价格:75.00
在代码中,BI 注释掉了 setw(16)、cin.sync() 和 cin.clear() 行,但无论这些行是否被注释掉,我都看不到输出中有任何变化。所以我的问题是,这些行的目的是什么?与没有的代码 B 相比,代码 A 通过这些额外的行获得了什么?是否有一些输入会导致 A 和 B 的输出不同,或者是肉眼无法看到的差异?此外,sets(n) 行中整数 n 的用途是什么。我已将此数字更改为不同的值,例如 16、78、100、10000 等,但这似乎也不会改变两个代码的输出。谢谢。