[英]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".
我想读取一个.txt 文件,这些行就像“名字姓氏;电话号码”。
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!编辑:感谢您的快速回复!
Two possible solutions:两种可能的解决方案:
One relatively simple way is to read fname
like you do now, then use std::getline
with ';'
一种相对简单的方法是像现在一样读取
fname
,然后使用带有';'
std::getline
as the separator (instead of the default newline) to get lname
.作为分隔符(而不是默认的换行符)来获取
lname
。 Then you could read into num
.然后你可以读入
num
。
Get fname
like you do now.像现在一样获取
fname
。 Then get lname;num
into a second string.然后将
lname;num
放入第二个字符串。 Find the semi-colon and create two sub-strings , one for lname
and one for num
. 找到分号并创建两个子字符串,一个用于
lname
,一个用于num
。 Then convert the string containing num
into an integer (with the caveat mentioned in my comment to the OP).然后将包含
num
的字符串转换为 integer (在我对 OP 的评论中提到了警告)。
You can pass ;
你可以通过
;
as a separator to getline
when extracting lname
.在提取
lname
时作为getline
的分隔符。
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;
}
You can use string.find to find the semicolon, and then use string.substr to split the string.您可以使用string.find查找分号,然后使用string.substr拆分字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.