简体   繁体   中英

C++: getline() ignoring first several characters

In my program, fin is an ifstream object and song is a string .

When the program runs, it opens music.txt and reads from the file. I try to read each line with: getline(fin,song);

I've tried all variations of getline but it keep ignoring the first 10 or so characters of each line before it starts picking up characters. For instance, if the song name is "songsongsongsongsongname," it might only pick up " songname."

Any ideas?

Here's the simplified code:

 void Playlist::readFile(ifstream &fin, LinkedList<Playlist> &allPlaylists, LinkedList<Songs*> &library) 
{
    string song;
    fin.open("music.txt");  
    if(fin.fail())          
    {
        cout << "Input file failed. No saved library or playlist. Begin new myTunes session." << endl << endl;
    }
    else
    {
        while(!fin.eof() && flag)
        {
                getline(fin, song);     
                cout << song << "YES." << endl;
                }
.....}

Give a try in this way,

...
else
{
    while(fin)
    {
        getline(fin, song);    //read first
        if(!fin.eof() && flag) //detecting eof is meaningful here because
        {                      //eof can be detected only after it has been read
            cout << song << "YES." << endl;
        }
    }
}

A fixed version:

void Playlist::readFile(std::string const& filename, ...) {
    std::ifstream fin(filename.c_str());
    if (!fin) throw std::runtime_error("Unable to open file " + filename);
    for (std::string song; std::getline(fin, song); ) {
        ...
    }
}

Most importantly I have removed the test of .eof() . You cannot use that for testing if you can read more and you also cannot use it for testing whether the previous read succeeded or not. Verifying that an earlier operation succeeded can be done by checking the fail flag, or most often by testing the stream itself.

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