Search code examples
c++file-iofstreamifstream

Read only user's names from txt file [C++]


ifstream file;
file.open("Data.txt");

string name;

while (file >> name) {
    cout << name << endl;
}

So i have a text file where the following information is stored about a user: Name, Weight, Height and previous heights. How would i only output the user's names and nothing else.

enter image description here


Solution

  • Read one line with std::getline and store the name read. Then discard the next four lines with file.ignore(std::numeric_limits<streamsize>::max(), '\n') to reach the next line with a name.

    Repeat until getline or ignore fail.

    Documentation for std::getline

    Documentation for std::istream::ignore

    Documentation for std::numeric_limits::max