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

关于C++读取文本文件首整数时调用stoi()触发Thread 1: signal SIGABRT错误的技术咨询

Fixing the std::invalid_argument Error When Reading Integers From a Text File

Hey there! Let's break down why you're hitting that SIGABRT error and fix your code properly.

What's Causing the Crash?

Looking at your code, the issue is clear: you're trying to convert an empty string to an integer with stoi(). Here's the problematic section:

string line;
// line is empty right now—you haven't read anything from the file yet!
string str = line;
N = std::stoi(str);

An empty string can't be converted to an integer, which triggers the std::invalid_argument exception that's crashing your program. On top of that, your file reading logic is out of order—you're trying to process data before you even read from the file.

Correct Approach to Read the File

Here's how to properly read your space-separated numbers, extract the first one into N, and handle the rest:

  1. Always check if the file opened successfully—this avoids silent failures if the file is missing or inaccessible.
  2. Read the line of data first before processing it.
  3. Use a stringstream to parse the line—this makes it easy to split space-separated values into integers without manual string handling.

Fixed Code

#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;

int main() {
    string line;
    ifstream myfile("div7.in");
    
    // First, verify the file opened correctly
    if (!myfile.is_open()) {
        cerr << "Error opening file! Check if the path is correct." << endl;
        return 1;
    }

    int N = -1;
    // Read the entire line of data from the file
    if (getline(myfile, line)) {
        stringstream ss(line);
        // Extract the first integer directly into N
        ss >> N;
        cout << "N: " << N << endl;

        // Optional: Read and print the remaining integers
        int num;
        cout << "Remaining numbers: ";
        while (ss >> num) {
            cout << num << " ";
        }
        cout << endl;
    } else {
        cerr << "Failed to read any data from the file!" << endl;
    }

    myfile.close();
    return 0;
}

Key Improvements Explained

  • File Validation: The !myfile.is_open() check catches cases where the file can't be accessed (e.g., wrong file path, missing file).
  • Stringstream Parsing: stringstream automatically handles whitespace, so you don't have to split the string manually. Using >> to read integers is safer than stoi() here—it won't throw an exception if the next token isn't a valid integer (instead, it sets the stream to a failed state, which you can check with ss.fail() if needed).
  • Logical Order: We read the file first, then process the data—this eliminates the empty string issue entirely.

Extra Tips

  • If your file has multiple lines of data, wrap the getline and stringstream logic in a while loop.
  • For graceful handling of invalid integer values, add error checking after reading:
    if (!(ss >> N)) {
        cerr << "Failed to parse the first value as an integer!" << endl;
        return 1;
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 17:12:45