当我运行我的代码,只打印了双重的小数部分。在另一页,我参加了一个双输入和打印出来的双重它输入的方式。但是,对于我下面的代码,它只是打印出小数。例如,当I输入1.95它只打印出0.95。为什么去掉第一个数字?我看到在我的代码没有什么指向这一点。
我在一个更简单的方法已经尝试过了,它的工作。而且我没有看到那会惹我的代码双任何问题。
#include <iostream>
using namespace std;
int main()
{
double price;
char user_input;
do
{
cout << "Enter the purchase price (xx.xx) or `q' to quit: ";
cin >> user_input;
if (user_input == 'q')
{
return 0;
}
else
{
cin >> price;
int multiple = price * 100;
if (multiple % 5 == 0)
{
break;
}
else
{
cout << "Illegal price: Must be a non-negative multiple of 5 cents.\n" << endl;
}
}
} while (user_input != 'q');
cout << price << endl;
}
当我输入1.95,我得到0.95。但输出应该是1.95。
问题包含在其他的答案:阅读的'q'
移除从流的第一个字符,才能够解析成double
。
A液:先读double
。如果读取失败,请检查输入的是'q'
。
#include <iostream>
#include <limits>
using namespace std;
int main()
{
double price;
while (true)
{
cout << "Enter the purchase price (xx.xx) or `q' to quit: ";
if (cin >> price)
{
// use price
}
else // reading price failed. Find out why.
{
if (!cin.eof()) // didn't hit the end of the stream
{
// clear fail flag
cin.clear();
char user_input;
if (cin >> user_input && user_input == 'q') // test for q
{
break; // note: Not return. Cannot print price if the
// program returns
}
// Not a q or not readable. clean up whatever crap is still
// in the stream
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
else
{
// someone closed the stream. Not much you can do here but exit
cerr << "Stream closed or broken. Cannot continue.";
return -1;
}
}
}
cout << price << endl;// Undefined behaviour if price was never set.
}
另一种合理的选择是阅读所有输入作为std::string
。如果string
不"q"
,试图将其转换为与double
或std::stod
一个std::istringstream
。
当在命令行键入1.95,可变user_input
被分配“1”,和price
被分配0.95。