线程 1:为 C++ 输入发出 SIGABRT 信号
Thread 1: signal SIGABRT for C++ Input
我正在尝试从如下所示的文件中读取输入:
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);
没有从文件读取数据到 line
。
添加
getline (myfile, line);
之前
string str = line; // a variable of string data type
从文件中读取一行。
添加检查以查看文件打开和读取是否成功将使您的代码更好。
我正在尝试从如下所示的文件中读取输入:
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);
没有从文件读取数据到 line
。
添加
getline (myfile, line);
之前
string str = line; // a variable of string data type
从文件中读取一行。
添加检查以查看文件打开和读取是否成功将使您的代码更好。