首页 > 解决方案 > 我应该如何格式化 getline 以不跳到代码的末尾?

问题描述

我是一名学习 c++ 的超级新学生,并创建了一个小型货币转换器,该转换器将字符串用于您正在访问的国家/地区的输入。使用正常的 std::cin >> 国家;该程序运行良好,但不会读取“多米尼加共和国”等国家/地区。我尝试使用 getline 但直接跳过国家输入到最后一个 else {} 语句。

    std::cout << "Enter how many US Dollars you want to convert: " << std::endl;
    std::cin >> USD;

    std::cout << "What country are you planning to visit?" << std::endl;
    std::getline(std::cin, country);


    if (country == "Canada") {
        conversion = USD * 1.2074;
        std::cout << USD << " US dollars converted into Canadian Dollars (CAD) is: " << std::endl;
        std::cout << conversion << " Canadian Dollars" << std::endl;
        std::cout << "Hit Y if you'd like to convert again or N to quit. " << std::endl;
        std::cin >> again;
    }
    else {
        std::cout << "Sorry, this converter only has major US tourist destinations." << std::endl;
        std::cout << "Please try another country. Hit Y if you'd like to try again or N to quit.";
        std::cin >> again;
    }

如何在运行 else 分支之前调整代码以实际接收输入?感谢你们!

标签: c++

解决方案


推荐阅读