Getline not reading first line...

Write your question here.

Hello, I am new here and new to C++. I am trying to read around 4,000 lines from a text file, each line holds a number starting at 1 and going around 4,000 but missing a few numbers here and there. For some reason the first line that is read is 2,977 every time I run the program instead of line 1. Any ideas?

Thanks in advance for the help!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <fstream>
#include <cstring>

using namespace std;

int main()
{
    string datastream;

    ifstream myFile ("test.txt");

  if ( myFile.is_open() )
  {
    while ( !myFile.eof() )
    {
        getline(myFile, datastream);
        cout << datastream << endl;
    }
    myFile.close();
  }

    return 0;
}
Firstly, your loop is wrong - as it is, the last thing it reads will be garbage. Never loop on eof! Instead, try this:
15
16
17
18
    while(getline(myFile, datastream))
    {
        cout << datastream << endl;
    }


Secondly, have you tried with a small input file and had the same problem? What does the start of your file look like?
edit.. nvm, not sure what you are doing wrong then.

it seems to work fine for me.
Last edited on
EDIT: I tried it with a new text file with new numbers and it still starts around halfway through the file...

Quick update.... The code works fine for small text files. When I changed my loop per L B's advice, the first line that is displayed is now 2,976 instead of 2,977. I can't figure out what I'm doing wrong here.

I copy/pasted the numbers that are in the text file, would that have something to do with it? Could it be a corrupt file?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <fstream>
#include <cstring>

using namespace std;

int main()
{
    string datastream;

    ifstream myFile ("RawData.txt");

    if ( myFile.is_open() )
    {
    while (getline(myFile, datastream))
    {
        cout << datastream << endl;
    }
    myFile.close();
    }
    else
    {
        cout << "Could not locate file" << endl;
    }

    return 0;
}


Thanks again for the help!
Last edited on
Hey guys, thanks for the quick reply's. I figured out the problem, it turns out it was my screen buffer on the command console was set tto be too small.
When in doubt, pipe output to a file ;)
Topic archived. No new replies allowed.