输入未使用某些文字读取

时间:2015-03-20 09:52:43

标签: c++ string cin

非常新的程序员,看似晦涩难懂的问题:

string currency = "???";
double amount = 0.0;
double amount_final = 0.0;
cin >> amount >> currency;
if (currency == "GBP"){
amount_final = amount*1.47;
}
 else if (currency == "Yen"){
    amount_final = amount*0.0083;
}
else if(currency == "Euro"){
    amount_final = amount*1.07;

一切正常,除非你输入"欧元"在这种情况下,它表现得像你没有输入任何东西并返回初始值。 一点点的测试告诉我,我遇到问题的唯一一次是,如果字符串的第一个字母是E或e,并且前面没有空格,那么我试过的任何其他值都可以正常工作。

TL; DR:如果我改变什么,除了"欧元"到"鱼"该计划有效,有什么用?

2 个答案:

答案 0 :(得分:2)

浮点解析器贪婪并消耗" E"它代表输入流的指数,留下" uro"作为输入流的其余部分。

基本上贪婪的解析在这里失败了,因为它是一个需要超前1的语法。(" E"后跟数字)。

答案 1 :(得分:0)

#include <iostream>
#include <string>

int main() {
    std::string currency = "???";
    double amount = 0.0;
    double amount_final = 0.0;
    std::cin >> amount >> currency;
    if (currency == "GBP"){
    amount_final = amount*1.47;
    }
    else if (currency == "Yen"){
        amount_final = amount*0.0083;
    }
    else if(currency == "Euro"){
        amount_final = amount*1.07;
    }
    std::cout << amount_final << std::endl;
}

[localhost functionTest]$ ./a.out 
11 GBP
16.17

[localhost functionTest]$ ./a.out 
11 Yen
0.0913

[localhost functionTest]$ ./a.out 
11 Euro
11.77

对不起我的情况是有效的,你总是使用金额货币吗?