views:

250

answers:

3

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;
                }
.....}
A: 

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.

Tronic
A: 

Thanks guys.

I was able to make that work, though it's acting a bit weird.

Now my output stream isn't working right. I'll getline a song, and then try to output it with:

cout << "Song: " << song << "*" << endl;

And instead of outputting: Song: song***

It outputs: ***g: song

Gabe
Sounds like `song` has a trailing `\r` on it. This may be the case if the file uses `\r\n` newlines but your `ifstream` only breaks off the `\n`.
ephemient
Get rid of `\r\n` line endings (filter with `dos2unix`) on your files beforehand. Or maybe `song.erase(str.find_last_not_of("\r\n")+1)` or something like that.
ephemient
That's it! Thanks so much. I had to convert the text file to UNIX mode.Thanks much, much, much.
Gabe
A: 

So I may have left in the "\r" as stated by ephemient. What does that mean and how can I fix it?

Gabe
Also, when I put in some that is, say, 8 letters long in the input file and then use getline, it picks up a 10 letter long name. How can I fix that to be accurate?
Gabe
Generally you should edit your original post to add more information, instead of answering it.
Bill