线程1:C++输入的SIGABRT信号



我正在尝试从如下文件中读取输入:

7
3
5
1
6
2
14
10

我试图保存整数N中的第一个数字,但我在使用stoi((时出错,它给了我错误";线程1:信号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) 

我做了一些研究,发现它抛出了错误,因为它无法将其转换为整数。如何从txt文件中读取输入并将其保存为整数?我使用Xcode作为IDE。我没有发现任何关于堆栈溢出的问题。提前感谢!我的整个代码如下:

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

你做了

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

而不从文件向CCD_ 1读取数据。

添加

getline (myfile, line);

之前

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

从文件中读取一行。

添加检查以查看文件打开和读取是否成功将使代码变得更好。

最新更新