You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

程序启动抛出异常:输入数量后触发substr逻辑错误排查

问题分析与解决

核心问题

当你用std::cin >> noOfInput读取输入的数字4时,输入缓冲区中会留下换行符(按下回车确认输入时产生的)。紧接着调用std::getline(std::cin, line)时,getline会直接读取这个换行符,导致line成为空字符串。

后续执行line.find_first_not_of(" ")时,因字符串为空,返回值是std::string::npos(即错误信息里的18446744073709551615,是size_t类型的最大值)。用这个非法位置调用substr,直接触发越界异常。

修复步骤

  1. 清除输入缓冲区的换行符:在std::cin >> noOfInput之后,调用std::cin.ignore()跳过缓冲区里的换行符,确保后续getline能正确读取下一行内容:

    int noOfInput; 
    std::cin >> noOfInput;
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // 忽略到换行符为止
    

    需包含<limits>头文件来使用std::numeric_limits。

  2. 补全未声明变量:代码中的line变量未声明,需添加std::string line;定义。

  3. 循环处理多行输入:输入包含4行商品数据,需用循环遍历处理所有输入:

    for (int i = 0; i < noOfInput; ++i) {
        std::getline(std::cin, line);
        // 后续解析逻辑
    }
    

修复后的示例代码

#include <iostream>
#include <string>
#include <limits>

int main()
{
    int noOfInput; 
    std::cin >> noOfInput;
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    std::string line;
    try
    {
        for (int i = 0; i < noOfInput; ++i) {
            std::getline(std::cin, line);
            auto start = line.find_first_not_of(" ");
            if (start == std::string::npos) {
                continue;
            }
            auto stop = line.find_first_of(" ", start);
            int quantity = std::stoi(line.substr(start, stop - start));
            std::cout << "读取到数量:" << quantity << std::endl;
        }
    }
    catch (const std::logic_error & ex)
    {
        std::cout <<"Logic Error: " << ex.what() << std::endl;
    }
    return 0;
}

额外注意事项

  • 解析字符串时,建议先判断start和stop是否为std::string::npos,避免因输入格式异常再次触发错误。
  • std::stoi可能因非数字字符抛出异常,解析前可先验证子串是否为合法整数。

内容的提问来源于stack exchange,提问作者Falcon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 00:57:13