格式操纵器 (c++)

Format manipulators (c++)

本文关键字:c++ 操纵 格式      更新时间:2023-10-16

setprecision(2) 和字段宽度操纵器不起作用。当我执行双减法时,它将数字四舍五入到小数。并且输入不是右对齐或字段宽度为 6。我做错了什么?

//Runs a program with a menu that the user can navigate through different options with via text input
#include <iostream>
#include <cctype> 
#include <iomanip>
using namespace std;
int main()
{
    char userinp;
    while (true)
    {   
        cout<<"Here is the menu:" << endl;
        cout<<"Help(H)      addIntegers(A)      subDoubles(D)           Quit(Q)" << endl;
        cin >> userinp;
        userinp = tolower(userinp);
        if (userinp == 'h')
        {   
            cout <<"This is the help menu. Upon returning to the main menu, input A or a to add 2 intergers." << endl;
            cout <<"Input D or d to subtract 2 doubles. Input Q or q to quit." << endl;
        }
        else if (userinp == 'a')
        {
            int add1, add2, sum;
            cout <<"Enter two integers:";
            cin >> add1 >> add2;
            sum = add1 + add2;
            cout << setw(6) << setiosflags(ios::right) << "The sum of " << add1 << " + " << add2 << " = " << sum << endl;
        }
        else if (userinp == 'd')
        {
            double sub1, sub2, difference;
            cout.fixed;
            cout <<"Enter two doubles:";
            cin >> sub1 >> sub2;
            difference = sub1 - sub2;
            cout << setw(6) << setiosflags(ios::right) << setprecision(2) << "The difference of " << sub1 << " - " << sub2 << " = " << difference << endl;
        }
        else if (userinp == 'q')
        {
            cout <<"Program will exit, goodbye!";
            exit(0);
        }
        else
        {
        cout <<"Please input a valid character to navigate the menu - input the letter h for the help menu";
        cout << "Press any key to continue" << endl;
        }
    }
}

width()是唯一不粘性的操纵器:它适用于下一个格式化的输出,在您的情况下适用于字符串文字的打印。您应该将 std::setw() 的使用放在要格式化的值的正前方,例如:

cout << std::right << std::setprecision(2) << "The difference of "
     << std::setw(6) << sub1 << " - "
     << std::setw(6) << sub2 << " = "
     << std::setw(6) << difference << 'n';

我不确定你指的是什么精度。您可能还想使用 std::fixed

为了改进 Dietmar 的答案,为了得到小数点后的两位数,

你需要
cout << std::right << std::fixed << std::setprecision(2) << "The difference of "
     << std::setw(6) << sub1 << " - "
     << std::setw(6) << sub2 << " = "
     << std::setw(6) << difference << 'n';

添加std::fixed可以解决您遇到的问题。

示范:

Here is the menu:
Help(H)      addIntegers(A)      subDoubles(D)           Quit(Q)
d
Enter two doubles:123.456
23.4
The difference of 123.46 -  23.40 = 100.06
Here is the menu:
Help(H)      addIntegers(A)      subDoubles(D)           Quit(Q)