1 #include<iostream>
2 using namespace std;
3
4 int main()
5 {
6 const double yen_to_euro=0.007215;
7 const double euro_to_dollar=1.12;
8 char currency;
9 double x;
10
11 while(currency!='q')
12 {
13 cout << "enter currency and unit(y , e, or d)";
14 cin >> x >>currency;
15
16 switch(currency){
17
18 case 'y':
19 cout <<"euro:"<< x*yen_to_euro<<" dollar:"<<x*yen_to_euro*euro_to_dollar<<'\n';
20 break;
21 case 'e':
22 cout <<"yen:"<< (x*(1.0/yen_to_euro))<<" dollar:"<<(x*euro_to_dollar)<<'\n';
23 break;
24 case 'd':
25 cout <<" yen:"<< x*(1.0/yen_to_euro)*(1.0/euro_to_dollar)<<" euro:"<<x*(1.0/euro_to_dollar)<<'\n';
26 break;
27 case 'q':
28 currency='q';
29 break;
30 default:
31 cout << "invalid";
32 break;
33
34 }
35
36 }
37
38
39 }
~ 上述代码的预期功能是将选定的货币(日元为y,欧元为e,d为美元)转换为其他货币。
例如,如果我想转换成12日元,我会输入:
12y
然后程序就会输出
欧元:0.08658美元:0.0969696欧元
然而,如果我要输入12e,我就会收到一个无限循环。重复检查代码,似乎没有任何逻辑错误。不过,我感觉到问题的根源与第14行的cin有关,因为如果分别取x和货币类型,如下所示:
cin>> x;
cin>> currency;代码工作正常,但我需要输入金额,然后按enter,然后按下表示货币类型的字符。有没有一种方法只在一行中输入,没有空格?
此外,为何会有这样的表现呢?这种不寻常的行为,通过无限循环,只有在我输入e代表欧元,Q代表退出。
发布于 2015-08-12 23:00:20
12e被解释为浮点数的开始,如12e03。但是没有结束,所以您的流出现了错误(故障位)。此状态将导致所有后续输入失败,直到清除故障状态为止。
您可以有一个内部循环来检查这些格式错误:
while (...) {
...
while ( (cin >> x >> currency).fail() && !cin.eof()) { // loops as long as there's input and it's invalid
cout << "invalid format";
cin.clear();
}
if (cin.eof()) // if there's no longer input stop looping
break;
...
}请注意,如果要确保在任何情况下都执行循环,则应该将currency初始化为与“q”不同的内容。
顺便说一句,如果输入12e(有空格),12将被解释为数字,并将x和e转换为货币,正如您所预期的那样。
发布于 2015-08-12 22:59:37
将cin >> x >>currency;替换为
try{
std::string myLine;
std::getline (std::cin, myLine); // store line into myLine.
currency = myLine.back(); // get last character from line.
myLine.pop_back(); // remove last character from myLine.
x = std::stod(myLine); // try to conver the rest of the string to a double.
}
catch (...) {
//The user typed in something invalid.
currency= 'i';
}同时,确保#include <string>
注意,此解决方案假定您使用的是C11。
发布于 2015-08-12 23:09:06
正如其他答案所解释的那样,12e指的是浮点数的科学表示法,因此currency不存储'e‘。
要在没有空格的单行中获取输入,您应该使用std::getline,然后解析输入字符串。
因为您知道最后一个字符总是表示货币,所以前面的字符可以使用std::stoi转换成一个数字。
https://stackoverflow.com/questions/31976776
复制相似问题