Click to See Complete Forum and Search --> : getline question!


pdeopura
May 28th, 2008, 09:24 PM
With the following code, I'm trying to read a .txt file line by line.

I want to read through the file until the last line.... Is my if statement correct in saying that if getline(is, line) exists? Will it skip every other line? If incorrect, what's a way to do it? Thanks in advance!




istream& operator>> (istream &is, const Song &song) // reads in the values of song
{

if ( getline(is, line) )
{
Song *currentSong = new Song(NULL, NULL, NULL);
getline(inf, currentSong->titleID, "___");
getline(inf, currentSong->artistID, "___");
inf.ignore(11, "___");
getline(inf, currentSong->albumID);
return is;
}
}

Duoas
May 29th, 2008, 12:54 PM
Your syntax needs a little help. Also, I think you've mixed some things. To gather information from a line you've read, you'll want to use a stringstream. Finally, you are creating a new Song instead of using the one targeted by the >> operator (which shouldn't be const). Finally, no version of getline() takes a string as its third argument, alas.

istream& operator >> (istream& ins, Song& song)
{
string line;
if (getline(ins, line))
{
stringstream ls(line);
getline( ls, song->titleID, '_' );
while (ls.peek() == '_') ls.get(); // skip consecutive '_'s
getline( ls, song->artistID, '_' );
while (ls.peek() == '_') ls.get(); // skip consecutive '_'s
getline( ls, song->albumID, '_' );
}
return ins;
}

Hope this helps.