我有一个包含大量数据的文本文件,实际上是学生列表。 结构如下:“姓名”“电话”“性别”“学生ID”“电子邮件”
以下是列表的示例:
Roger Pont 70778745 M 20120345 [email protected] Tommy Holness 5127438973 M 20120212 [email protected] Lee Kin Fong 864564456434 F 30245678 [email protected]
数据存储在文本文件中,我已经使用getline()函数将每一行转换为字符串。
那就是:学生[0]包含“Roger Pont 7077874567 M 20120345 [email protected]”
我的任务是按照StudentID的升序对记录进行排序。
我的问题是我想将字符串拆分成不同的变量类型。 但是,由于某些名称之间有更多的空格而且电话号码由不同的长度组成,我不能这样使用输入和输出流: stream >> name [i] >> tel [i] >> gender [i] >> StudentID [i] >> email [i];
我有什么想法可以将字符串拆分成不同的变量?
提前致谢。
备注:我已经读过这个(Splitting a string into multiple variables in C++),但与那种情况不同,我没有特定的模式,比如在表示年龄的整数之前加上“age”这个词。
Roger Pont 70778745 M 20120345 [email protected]
Tommy Holness 5127438973 M 20120212 [email protected]
Lee Kin Fong 864564456434 F 30245678 [email protected]
查看上面的数据,如果我们向后处理每一行,那么问题就会变得非常简单:
N
。words[N-1]
=>电子邮件地址words[N-2]
=> student id。这给了你足够的暗示。
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
#include <iterator>
#include <cassert>
struct student
{
std::string name;
std::string phone;
std::string gender;
std::string student_id;
std::string email;
};
int main()
{
std::vector<student> students;
std::string line;
while(std::getline(std::cin, line))
{
std::istringstream ss(line);
std::istream_iterator<std::string> begin(ss), end;
std::vector<std::string> words(begin, end);
assert(words.size() >= 5);
int n = words.size() - 1;
student s { words[0], words[n-3], words[n-2], words[n-1], words[n] };
for (int i = 1 ; i < n - 3 ; i++) s.name += " " + words[i];
students.push_back(s);
}
//printing
for(auto && s : students)
std::cout << "name = " << s.name << "\n"
<< "phone = " << s.phone << "\n"
<< "gender = " << s.gender << "\n"
<< "student_id = " << s.student_id << "\n"
<< "email = " << s.email << "\n\n";
}
Roger Pont 70778745 M 20120345 [email protected]
Tommy Holness 5127438973 M 20120212 [email protected]
Lee Kin Fong 864564456434 F 30245678 [email protected]
name = Roger Pont
phone = 70778745
gender = M
student_id = 20120345
email = [email protected]
name = Tommy Holness
phone = 5127438973
gender = M
student_id = 20120212
email = [email protected]
name = Lee Kin Fong
phone = 864564456434
gender = F
student_id = 30245678
email = [email protected]
现在花一些时间来理解代码。我向您展示的代码是使用C ++ 11编写的。它演示了Modern C ++的许多习语。
希望有所帮助。
#include <iostream>
#include <vector>
#include <sstream>
using namespace std;
std::vector<std::string> strings;
std::istringstream f("Roger Pont 70778745 M 20120345 [email protected]");
std::string s;
while (std::getline(f, s, ' ')) {
std::cout << s << std::endl;
strings.push_back(s);
}
这有一个问题,两个单词之间的间距大于1个空格''。