阵列分段错误

Segmentation fault with array

本文关键字:错误 分段 阵列      更新时间:2023-10-16

我正在编写一个相当简单的代码,将存储在文件中的整数输入到中等大小的数组中,但是在编译和运行代码时,它给出了分段错误错误,任何人都可以纠正我犯错误的地方,代码是

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
int main()
{
    int arr[100000];
    ifstream f;
    f.open("IntegerArray.txt");
    string line;
    if (f.is_open())
    {
        int i=0;
        while (f.good())
        {
            getline(f,line);
            arr[i++] = atoi(line.c_str());
        }
        f.close();
    }
    else
        cout<<"file not open";
    return 0;
}
在用

getline() 从文件中删除一行后,应该检查流是否存在潜在错误,例如使用 .fail() ,它:

如果为流设置了故障位或坏位错误状态标志,则返回 true。

while (f.good())
{
    getline(f,line);
    if (f.fail()) {
        cout << "Corrupt data" << endl; // example output
        break;
    }
    // everything ok, continue with logic
    arr[i++] = atoi(line.c_str());
}