简体   繁体   中英

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;
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM