读取txt文件时"Debug Assertion Failed"

Geo*_*iev 0 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
Run Code Online (Sandbox Code Playgroud)

我的程序崩溃,出现以下错误:

在此输入图像描述

该程序读取文件的一些内容,直到某一点: 在此输入图像描述

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

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;
}
Run Code Online (Sandbox Code Playgroud)

此方法是以下类的一部分: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);
};
Run Code Online (Sandbox Code Playgroud)

nvo*_*igt 6

char townName[] = "";
Run Code Online (Sandbox Code Playgroud)

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