繁体   English   中英

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

[英]Thread 1: signal SIGABRT for C++ Input

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

7
3
5
1
6
2
14
10

我正在尝试将第一个数字保存在 integer 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) 

我做了一些研究,发现它抛出了错误,因为它无法将其转换为 integer。 如何从 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

从文件中读取一行。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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