0

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!

hemmy
  • 3
  • 2
  • 2
    Pro-tip: Don't use integers for phone-numbers! Phone-numbers can contain leading zeroes, something that an `int` can't handle. A phone-number can also contain leading explicit `+`, which are also lost in the conversion. – Some programmer dude May 26 '20 at 11:00
  • Also just semantically/logically they are not really numbers, but strings of digits/characters – Asteroids With Wings May 26 '20 at 13:25

3 Answers3

2

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).

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

You can pass ; as a separator to getline when extracting lname.

std::ifstream file("names.txt");

for (std::string line; getline(file, line);) {
    std::istringstream iss(line);
    std::string fname, lname;
    int num;
    iss >> fname;
    getline(iss, lname, ';');
    iss >> num;
}
Caleth
  • 52,200
  • 2
  • 44
  • 75
0

You can use string.find to find the semicolon, and then use string.substr to split the string.

miep
  • 119
  • 1
  • 7