阵列分段错误
Segmentation fault with array
我正在编写一个相当简单的代码,将存储在文件中的整数输入到中等大小的数组中,但是在编译和运行代码时,它给出了分段错误错误,任何人都可以纠正我犯错误的地方,代码是
#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());
}
相关文章:
- 在某些循环内使用vector.push_back时出现分段错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 当我的阵列太大时出现分段错误
- 分段错误当我试图运行程序时出错
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 尝试使用集合函数时出现分段错误
- 我无法缩小此分段错误的原因
- g++的分段错误(在NaN上使用to_string两次时)
- 为什么我使用 std::copy() 收到运行时错误(分段错误)?
- 为什么我的代码包含错误分段错误(核心转储)?
- 为什么会出现此错误?- 分段错误(核心转储)
- 意外的运行时错误(分段错误)
- C++将文本文件读入数组,运行错误:分段错误
- mmap 错误:分段错误/指针无效错误
- 在我的代码中找不到错误....分段错误
- 错误:分段故障(核心转储)阵列
- 用string.h将错误分段到队列中
- c++字符串流转换错误:分段错误
- 为什么我的代码显示错误分段错误(核心转储)