I've got a chunk of code that opens up a txt file with 5 or 6 lines inside. I only need to grab the first line of the txt file and put it inside of a variable. The problem is that when I use this code, instead of grabbing the first line, it some how ends up with the last.

Check it out:

ifstream musicCheck ("data/downloaded/music/music.txt");
  if (musicCheck.is_open())
  {
    while ( musicCheck.good() )
    {
                for(int v = 0; v > 1; v++){
      getline(musicCheck,songsUnlockedString);
              }

    }
    musicCheck.close();
  }

Music.txt:

4
stranger
data/sounds/stranger/
stranger2
datasks
stranger3
ekuer3
stranger4
elfjehfe

Output of getline:

elfjehfe

So does anyone have any ideas? I'm guessing that the while loop just keeps on looping around until the end of the file is reached, but i'm not sure how to stop it.


Thanks :)

Edited 6 Years Ago by mybluehair: n/a

i don't get the for loop

I put that in there to see if I could get it to quit after one time through the loop. That didn't work either

I've got a chunk of code that opens up a txt file with 5 or 6 lines inside. I only need to grab the first line of the txt file and put it inside of a variable. The problem is that when I use this code, instead of grabbing the first line, it some how ends up with the last.

Check it out:

ifstream musicCheck ("data/downloaded/music/music.txt");
  if (musicCheck.is_open())
  {
    while ( musicCheck.good() )
    {
                for(int v = 0; v > 1; v++){
      getline(musicCheck,songsUnlockedString);
              }

    }
    musicCheck.close();
  }

Music.txt:

4
stranger
data/sounds/stranger/
stranger2
datasks
stranger3
ekuer3
stranger4
elfjehfe

Output of getline:

elfjehfe

So does anyone have any ideas? I'm guessing that the while loop just keeps on looping around until the end of the file is reached, but i'm not sure how to stop it.


Thanks :)

//make sure you just opened musicCheck.txt
   //initializsongsUnlockedString string      
  ifstream musicCheck ("data/downloaded/music/music.txt");
  if (musicCheck.is_open())
  {
    int i=0;
    while ( musicCheck.good() )
    {
           if(i=0){
      getline(musicCheck,songsUnlockedString);
      i++;
              }
            }
    }
    musicCheck.close();
  }

G'luck

Edited 6 Years Ago by geojia: n/a

Wait, you only want the first line -- so what're all those loops for?

ifstream musicCheck( "..." );
if (musicCheck.is_open())
{
  // The file is open, so read the very first line
  getline(musicCheck,songsUnlockedString);
  // Now that we've read it, we're done. No loops needed.
}
musicCheck.close();

Hope this helps.

This article has been dead for over six months. Start a new discussion instead.