c++ - 在if语句C++中意外中断

标签 c++ visual-c++

该程序将日元,欧元或英镑(取决于用户输入)转换为美元。
我要问2个用户输入-双倍金额(要转换的货币)和char货币(以确定要转换为美元的货币)。
样本输入:1y
样本输出:1日元= 0.0094美元。
问题出在if-else块中,当我尝试将欧元转换为美元时,它打破了while循环。这是我的代码:

double amount; // the amount of money to be converted
char currency; // to determine the currency in which the money is being entered in.
    while (cin >> amount >> currency) {
        if (currency == 'y' || currency == 'Y') {
            cout << amount << " yen(s) = " << (amount * 0.0094) << " dollar(s).\n";
        }
        else if (currency == 'e' || currency == 'E') {
            cout << amount << " euro(s) = " << (amount * 1.13) << " dollar(s).\n";
        }
        else if (currency == 'p' || currency == 'P') {
            cout << amount << " pound(s) = " << (amount * 1.25) << " dollar(s).\n";
        }
        else {
            cout << "Sorry I did not recognize the currency! Please enter 'y','e' or 'p'.\n";
        }
        cout << "Please enter the amount of money and corresponding currency to covert to  dollars: ";
    }
作为证据,这里是我输入和输出的图像:
欧元转换为美元错误一

欧元转换为美元错误二

最佳答案

提供实际答案,因为我无法在评论中提供;这是获取相关用户输入并保持相同语法的另一种方法。假定输入字符串的最后一个字符是货币字符。您可以检查最后一个字符是否是有效的货币字符,但这是简化的版本。

#include <iostream>
#include <string>

int main() {
    std::string input_string;
    std::getline(std::cin, input_string);

    if(input_string.size() >= 2) {
        char currency = input_string[input_string.size() - 1];
        input_string[input_string.size() - 1] = '\0';
        double amount = std::stof(input_string);

        std::cout << amount << std::endl;
        std::cout << currency << std::endl;
    }
}

关于c++ - 在if语句C++中意外中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62552352/

相关文章:

c++ - ATL 库 :warning LNK4254 and LNK4078

C++ Diamond 控制台输出问题

c++ - 我如何能够在 1 字节的普通字符串中存储日文字符?

linux - Linux中有没有类似_clearfp()和_statusfp()的函数?

c++ - 将 UTC 转换为本地

c++ - 类型函数从类型 T 到类型积分,其中 sizeof(integral) >= sizeof(T)

c++ - 将 uint 传递给着色器会更改其值

c++ - const 参数的模板参数推导

c++ - 请帮助我理解链表C++中的运算符重载=

c++ - 字符 *newx=p+strlen(str1);这将如何执行,因为 strstr 将返回指向另一个字符串的第一个匹配字符的指针