Thread: Simple file input question?

  1. #1
    Registered User
    Join Date
    May 2007

    Simple file input question?

    Evening all,
    I'm using the code:

    if (myfile.is_open())
        while (! myfile.eof() )
          for(int b=0;b<PlayListLength;b++)
          getline (myfile,line);
          Title = line;
          getline (myfile,line);
          Artist = line;
          getline (myfile,line);
          Length = line;
          Playlist[b] = new Mp3(Title, Artist, Length);
    To read from a file and use three lines at a time to create a new mp3 within an array. I need the third value (Length) to be read as an int instead of a string.

    Can anyone help?!

    Thank you very much.

    Leigh Rogers

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    You can use formatted input with the overloaded operator>> for input streams. I am guessing that both Title and Artist are C++ strings, so you really do not need to use the line variable. Your nested loops is likely to be problematic, since if the input file has more Mp3s than your array allows, you will find that it overwrites some of the earlier Mp3s. You should probably use a std::vector instead. You probably should not control the loop with myfile.eof() anyway. One possibility is:
    for (int b = 0; myfile.good() && b < PlayListLength; b++)
        if (getline(myfile, Title))
            getline(myfile, Artist);
            myfile >> Length;
            myfile.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
            Playlist[b] = new Mp3(Title, Artist, Length);
    Out of curiosity, are you sure you need to store the Mp3 objects via an array of pointers?
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Data Structure Eror
    By prominababy in forum C Programming
    Replies: 3
    Last Post: 01-06-2009, 09:35 AM
  2. fscanf in different functions for the same file
    By bchan90 in forum C Programming
    Replies: 5
    Last Post: 12-03-2008, 09:31 PM
  3. help with text input
    By Alphawaves in forum C Programming
    Replies: 8
    Last Post: 04-08-2007, 04:54 PM
  4. quick question: File Input
    By meltingdude in forum C Programming
    Replies: 1
    Last Post: 04-08-2003, 02:02 AM
  5. File Input and Output, simple.
    By Vber in forum C Programming
    Replies: 5
    Last Post: 11-17-2002, 02:57 PM