格式操纵器 (c++)
Format manipulators (c++)
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)
相关文章:
- C++setiosflags函数操纵器-未确定的缩进
- C++表达SFINAE和ostream操纵器
- 操纵安卓相机的深度图导致应用程序崩溃
- 什么是现实中的"endl"(或任何输出操纵器)?它是如何实现的,它如何与操作员<<一起工
- 有关具有编译错误的操纵列表的问题
- C++自定义流操纵器,用于更改流上的下一个字符串
- 如何使用自定义流操纵器在类实例中保存数据
- 如何键入用于const对象的自定义io操纵器
- 如何实现接受参数的自定义流操纵器?
- I/O 操纵器错误或临时延长寿命由 const 参考?
- 如何编码为像 STL IO 操纵器函数这样的样式?
- 从QML ListView中QABStractListModel中的数据操纵数据
- 一系列宣言和操纵
- 保证原子性的单位操纵
- 操纵桌面图标的位置
- 输出操纵器 std::ends 是否向输出缓冲区添加空字符?
- 位操纵:更难掷硬币
- 如何操纵指针代表C 的对象
- 使用一系列指针对计算机来操纵指向(C )的指针
- C 操纵器,可以将SetPrecision Manip与SetFill Manip相结合