Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to read n to n + i lines in c++?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This is my current output that I get:

5
Name1
Name2
Name3
Name4

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading