Search code examples
c++ifstreamsstream

C++: Reading a line as : 'string string;int'


I have started coding lately(school curriculuim) and ran into a little problem. I want to read a .txt file, the lines are like "firstname lastname;phonenumber".

ifstream file("names.txt");

    string line, fname, lname;
    int num;

    while (getline(file, line)) {
        istringstream iss(line);
        iss >> fname >> lname >> num;
    }

So the problem is that the lastname is lastname + ";" + phone number and I don't know how to separate them. Any help is appreciated :)

Edit: Thanks for the quick replies!


Solution

  • Two possible solutions:

    1. One relatively simple way is to read fname like you do now, then use std::getline with ';' as the separator (instead of the default newline) to get lname. Then you could read into num.

    2. Get fname like you do now. Then get lname;num into a second string. Find the semi-colon and create two sub-strings, one for lname and one for num. Then convert the string containing num into an integer (with the caveat mentioned in my comment to the OP).