c++xcodefile-iosigabrt

Thread 1: signal SIGABRT for C++ Input


I am trying to read input from a file that looks like this:

7
3
5
1
6
2
14
10

I am trying to save the first number in the integer N but I am getting and error when using stoi() and it gives me the error "Thread 1: signal SIGABRT":

libc++abi.dylib: terminating with uncaught exception of type std::invalid_argument: stoi: no conversion
terminating with uncaught exception of type std::invalid_argument: stoi: no conversion
(lldb) 

I did some research and found that it threw the error because it couldn't convert it to an integer. How do I read input from txt files and save them in integers? I'm using Xcode as the IDE. I didn't find anything on stack overflow with this specific question. Thanks in advance! My entire code is below:

 #include <iostream>
#include <string>
#include <fstream>
#include <sstream>

using namespace std;

int main() {
    
    string line;
    ifstream myfile ("div7.in");
    int N = -1;
    
    string str = line; // a variable of string data type
    N = std::stoi(str);
    cout << '\n N: ' << N << endl;
    
    
    while (getline (myfile, line)){
        cout << line << "\n";
    }
    myfile.close();
   
    return 0;
}

Solution

  • You did

    string str = line; // a variable of string data type
    N = std::stoi(str);
    

    without reading data from the file to line.

    Add

    getline (myfile, line);
    

    before

    string str = line; // a variable of string data type
    

    to read a line from the file.

    Adding check to see if file opening and reading are successful will make your code better.