首页 > 解决方案 > 我无法理解 C++ 中 setw(n) 函数的用途

问题描述

我一直在从教科书中学习 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 等,但这似乎也不会改变两个代码的输出。谢谢。

标签: c++setw

解决方案


让我们看一下这段代码:

#include <iostream>
#include <iomanip>

int main() {
    double value = 1234567890.321654987;
    
    std::cout << value << '\n';
    
    std::cout << std::setw(20) << value << '\n';
    std::cout << std::setw(2) << value << '\n';
    
    
    std::cout << std::setprecision(2) << value << '\n';
    std::cout << std::setprecision(20) << value << '\n';
}

它打印:

1.23457e+09
         1.23457e+09
1.23457e+09
1.2e+09
1234567890.321655035

宽度是最小字符数:如果需要,可以添加空格。

精度是位数。第一次打印使用默认精度(显然是 6)。


推荐阅读