CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Mar 2009
    Posts
    48

    Reading text file - extra line

    Help. Anyone tell me why this code outputs 7 lines (the last line twice) while the file contains 6 lines?

    cout << "read msgfile\n";
    ifstream msgfile ("script1.msg");
    while (msgfile.good()) //if not at end of file, continue reading
    {
    // load vector with deffile
    msgfile >> line;

    vectormsgfile.push_back (line);
    cout << line << "\n";
    }
    msgfile.close();

    Cheers and tx

  2. #2
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: Reading text file - extra line

    Because immediately after reading the last line, msgfile.good() still returns true. Only after the next attempted read does it return false, but by then you would have pushed back into the container again and printed the line.

    As such, it would be better to write say:
    Code:
    cout << "read msgfile\n";
    ifstream msgfile("script1.msg");
    while (getline(msgfile, line))
    {
        // load vector with deffile
        vectormsgfile.push_back(line);
        cout << line << "\n";
    }
    msgfile.close();
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  3. #3
    Join Date
    Mar 2009
    Posts
    48

    Red face Re: Reading text file - extra line

    Many tx laserlight

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured