zyf419512 2023-05-22 15:46 采纳率: 0%
浏览 19

如何解决?(语言-c++)

已知的std::stoi(const std::string& str)函数可以把字符串转为整数,如果输入的字符串不是数字或者数字串过长,会抛出中std::logic_failure的std::invalid_argument子类 或std::out_of_range子类 异常。
写一个允许用户输入字符串,输出对应整数的程序。
要求:除非用户想退出,否则输入的字符串不符合要求也可以正常继续进行。

  • 写回答

3条回答 默认 最新

  • 创意程序员 2023-05-22 15:51
    关注

    可以使用 try catch 的方式进行转换并捕获错误,这样程序就能在 while 里面一直运行。示例代码如下:

    #include <iostream>
    #include <string>
    #include <stdexcept>
    
    int main() {
        std::string input;
    
        while (true) {
            std::cout << "请输入一个字符串,或输入 q 退出: ";
            std::cin >> input;
    
            if (input == "q") {
                break;
            }
    
            try {
                int number = std::stoi(input);
                std::cout << "对应的整数为: " << number << std::endl;
            } catch (const std::invalid_argument& e) {
                std::cout << "无法转为整数。" << std::endl;
            } catch (const std::out_of_range& e) {
                std::cout << "超出整数可表示的范围。" << std::endl;
            }
        }
    
        return 0;
    }
    
    评论 编辑记录

报告相同问题?

问题事件

  • 创建了问题 5月22日