分段故障核心转储的并行阵列

Segmentation fault Core dumped parallel arrays

本文关键字:并行 阵列 转储 故障 核心 分段      更新时间:2023-10-16

我对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,则会出现分段错误。