c++ - 读取 txt 文件时出现 "Debug Assertion Failed"

标签 c++ file

<分区>

我正在尝试创建一个 C++ 程序来读取包含以下内容的文本文件:

ITEMS 8
ABERDEEN    430082  3.2  5.0
GLASGOW     629501  2.0  1.5
PAISLEY     74170   1.0  1.0
MOTHERWELL  30311   3.0  1.0
EDINBURGH   430082  5.0  1.3
FALKIRK     32379   3.1  1.2
LINLTHGOW   13370   3.0  1.5
DUNDEE      154674  3.2  3.1

我的程序因以下错误而崩溃:

enter image description here

程序读取文件的一些内容直到某一点: enter image description here

我注意到的一件有趣的事情是,我的每个城镇的 X 和 Y 坐标都应该是 double 的,而当我读取文件时,一些 X/Y 是整数或 double (不知道这是怎么发生的)。我将每个城镇作为城镇对象存储在这样的城镇区域中: 这是我从文件中读取的方法:

bool TownReader::readDatafile(char *datafile)
{
    ostringstream errorString;

    ifstream inDatastream(datafile, ios::in);

    if (!inDatastream)
    {       
        errorString << "Can't open file " << datafile << " for reading.";
        MessageBoxA(NULL, errorString.str().c_str(), "Error", MB_OK | MB_ICONEXCLAMATION);
        return false;
    }

    cout << "Reading from file: " << datafile << endl; 

    readUntil(&inDatastream, "ITEMS");
    //Read the number of towns...
    inDatastream >> numTowns;
    //reserve the nesessery memory...
    TownPtr = new Town[ numTowns ];

    cout << "Number of towns: " << numTowns << endl;

    for (int i = 0; i < numTowns; ++i)
    {
        Town newTown;
        char townName[] = "";
        double townX = 0.0;
        double townY = 0.0;
        int townPopulation = 0;
        inDatastream >> townName >> townPopulation >> townX >> townY;
        cout << "Town name: " << townName << endl;
        cout << "Town pop: " << townPopulation << endl;
        cout << "Town X: " << townX << endl;
        cout << "Town Y: " << townY << endl;

        newTown.setName(townName);
        newTown.setPopulation(townPopulation);
        newTown.setX(townX);
        newTown.setY(townX);

        TownPtr[i] = newTown;
    }

    return true;
}

此方法是以下类的一部分:TownReader。这是类的标题:

class TownReader
{
private:
    Town *TownPtr;
    int numTowns;

public:
    TownReader(void);
    bool readDatafile(char *filename);
    bool writeDatafile(char *filename);

    bool readUntil(std::ifstream *inStream, char *target);


    Town *getTowns(void);
    int getNumTowns(void);

    bool writeBlankRecords(char *datafile, int num);
    bool writeTownsBinary(char *datafile);
    bool readSpecifiedRecord(char *datafile);
    bool writeSpecifiedRecord(char *datafile);
};

最佳答案

char townName[] = "";

这是一个大小为 1 的数组。您无法向其中读取任何内容。请在使用 C++ 时放弃使用 char 数组并使用 std::string

关于c++ - 读取 txt 文件时出现 "Debug Assertion Failed",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35895925/

相关文章:

c++ - dynamic_cast以意外的方式成功

c++ - 如何通过 HttpReceiveHttpRequest() 使用 HTTPS?

php - 上传前是否可以显示 tmp 文件夹中的图像?

python - 如何在 Python 中检测文件是否为二进制(非文本)文件?

c++ - 如何在类初始值设定项中设置 union ?

c++ - 使用复制昂贵的类作为 std::map 中的映射值是否有效?

C++ fstream 继续读取相同的前 5 行?

c# - 该进程无法访问该文件,因为它正被另一个使用 streamwriter 的进程使用

c++ - 从文本文件读取矩阵到二维整数数组 C++

c# - 覆盖 BMP 文件,无法删除,因为它已被另一个进程使用 - Dispose,使用无效