0

This is the file to be read

5
Name1
Name2
Name3
Name4
Name5

My current code to read this is:

void readData(string fileName, string names[], int n) {
    ifstream myFile("file.txt");
    string line;

    if (myFile.is_open())
    {
        myFile >> n;  // read first line
        cout << n; 

        for (int i = 0; i < n; ++i) {
            getline(myFile, line);
            names[i] = line;
            cout << names[i] << endl;
        }
    }
}

I want to put the names into the array names[], but even though n = 5, it seems like it runs only 4 times. Why is that?

This is my current output that I get:

5
Name1
Name2
Name3
Name4
william
  • 52
  • 4

1 Answers1

0

You didnt read the whole first line when you did myFile >> n. So the first getline just read the rest of that line, which is empty

Do

 myFile >> n; 
 getline(myFile, line); // read rest of line

or

 getline(myFile, line); // read whole line
 n =  stoi(line);   // convert to int
pm100
  • 48,078
  • 23
  • 82
  • 145