简体   繁体   中英

reading from a file c++ [program halts at reading put]

I'm having a problem reading in from a file, I feel disoriented and I cannot seem to find the error within my code(I'm sure it's a minor mistake because I've done this before) This a homework assignment. The assignment calls for the constructor to load in contents from a file. However, the program halts after reading in the first line.

tree::tree()
    {

    root = NULL;
    load();
}

int tree::load()
{
    ifstream inFile;

    definition anEntry;

    char title[TITLE], info[INFO];

    inFile.open("CS_terms.txt");

    if (inFile.is_open())
    {
        cin.get(title, TITLE, ':');
        cin.ignore(TITLE, ':');
        cin.get(info, INFO, '\n');
        cin.ignore(INFO, '\n'); 

        anEntry.createEntry(title, info);
        insert(anEntry);

        while (inFile.is_open() && !inFile.eof())
        {
            cin.get(title, TITLE, ':');
            cin.ignore(TITLE, ':');
            cin.get(info, INFO, '\n');
            cin.ignore(INFO, '\n'); 
            anEntry.createEntry(title, info);
            insert(anEntry);
        }
        inFile.close();
        return 1;
    }
    else
    {
        cout << "No File" << endl;
        return 0;
    }
}

You should replace this line:

if (inFile)

by this

if (inFile.is_open())

and this:

while (inFile.is_open() && !inFile.eof())

by

while (inFile.good()) 

尝试用inFile.get()替换cin.get() inFile.get()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM