'How to read n to n + i lines in c++? [duplicate]
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
Solution 1:[1]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | pm100 |
