分段故障核心转储的并行阵列
Segmentation fault Core dumped parallel arrays
我对C++很陌生,我只是想读取一个文本文件,该文件每行有一个字符串和两个十进制数字。当我试图将它们读取到数组中时,我遇到了分段错误。。。。我仍然在学习数组,不明白为什么这对我的生活不起作用
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
const int ARRAY_SIZE = 1000;
string fileLocation;
ifstream newList;
string city[ARRAY_SIZE];
double lowTemp[ARRAY_SIZE];
double highTemp[ARRAY_SIZE];
int LoadData (char com);
void ShowAll (int count);
int main()
{
char command;
cout << "Welcome to David's Libary Database!" << endl << endl << "(L)oad File, (S)how All, (F)ind City, (Q)uit ";
cin >> command;
LoadData(command);
return 0;
}
int LoadData(char com)
{
int index = 0;
double tempLow, tempHi;
string singleCity;
if(com == 'l' || com == '1' || com == 'L')
{
cout << "Please provide a file path: ";
cin >> fileLocation;
newList.open(fileLocation.c_str());
if(!newList.is_open())
{
cout << "Please provide a file path: ";
cin >> fileLocation;
newList.open(fileLocation.c_str());
if(!newList.is_open())
{
return -1;
}
}
while(!newList.eof())
{
newList >> singleCity >> tempLow >> tempHi;
city[index] = singleCity;
lowTemp[index] = tempLow;
highTemp[index] = tempHi;
index++;
}
cout << index +1 << " record(s) found." << endl;
cout << city[0];
newList.close();
newList.clear(std::ios_base::goodbit);
}
return 0;
}
不要使用while(!newList.eof())
检查文件结尾。您应该将其修改为,
while(newList >> singleCity >> tempLow >> tempHi)
{
city[index] = singleCity;
lowTemp[index] = tempLow;
highTemp[index] = tempHi;
index++;
}
前提是该城市的字符之间没有任何空格。您的输入文件应该是,
NY 23 24
LA 13 18
如果您的输入文件为,它将失败
New York 23 24
Los Angeles 13 18
您应该检查它是否超出了city[]
数组的范围。
除非您的文件中恰好有1000多个条目,否则没有明显的seg错误原因。
我猜一下,你出错的原因是你的阅读循环不正确。全面测试你的阅读是否成功。若读取失败,但不是因为文件的末尾,那个么循环将永远进行下去。我认为这可能就是本案中发生的事情。在任何情况下,newfile.eof()
都不会做您明显认为它会做的事情,如果您在文件末尾,它会而不是测试。
这是写循环的正确方法,试试这个,看看它是否对有任何影响
while (newList >> singleCity >> tempLow >> tempHi)
{
city[index] = singleCity;
lowTemp[index] = tempLow;
highTemp[index] = tempHi;
index++;
}
查看此代码如何实际测试读取是否成功(通过将读取本身置于while条件中)。
另一个错误
cout << index +1 << " record(s) found." << endl;
太多了,应该是
cout << index << " record(s) found." << endl;
首先,尝试使用g++ -g
进行编译,然后运行gdb
以获得堆栈跟踪,这样您就可以知道段故障发生在哪里。
在您的代码中:
while(!newList.eof())
{
newList >> singleCity >> tempLow >> tempHi;
city[index] = singleCity;
lowTemp[index] = tempLow;
highTemp[index] = tempHi;
index++;
}
如果索引大于ARRAY_SIZE,则会出现分段错误。
相关文章:
- OpenMP阵列性能较差
- 如何将三维尺寸不固定的三维阵列展平为一维阵列
- 当我的阵列太大时出现分段错误
- C++17中的并行执行策略
- 并行用于C++17中数组索引范围内的循环
- 如何在Elixir中调用递归函数并行
- OpenMP:并行更新数组总是需要减少数组吗
- 位阵列上的快速AND运算
- 如何使用OpenMP并行这两个循环
- 英特尔并行工作室 2015 C++中的 2D 动态分配全局阵列
- 从一个文件读取到三个并行阵列
- 比较从文本文件中读取的并行阵列
- 如何自动并行化堆阵列
- 分段故障核心转储的并行阵列
- 使用并行阵列的初学者编程学生
- 并行写入阵列
- 使用OpenMP原子并行更新矩阵列
- 与CUDA并行传输阵列
- C++并行化:快速"reinitialize"阵列
- CUDA 并行化依赖的 2D 阵列