Reputation: 3
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!
Upvotes: 0
Views: 486
Reputation: 409462
Two possible solutions:
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
.
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).
Upvotes: 2
Reputation: 63162
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;
}
Upvotes: 1
Reputation: 119
You can use string.find to find the semicolon, and then use string.substr to split the string.
Upvotes: 0