Roger Pont 70778745 M 20120345 hills@school.edu
Tommy Holness 5127438973 M 20120212 tommy@school.edu
Lee Kin Fong 864564456434 F 30245678 fong@school.edu
看上面的数据,如果我们把每一行都倒过来处理,那么问题就变得很简单了:
- 将单词分成一行。说字数是
N
。
- 最后一个词是 email,即
words[N-1]
=> 电子邮件地址
- 倒数第二个是studentid,即
words[N-2]
=> 学生 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 hills@school.edu
Tommy Holness 5127438973 M 20120212 tommy@school.edu
Lee Kin Fong 864564456434 F 30245678 fong@school.edu
输出:
name = Roger Pont
phone = 70778745
gender = M
student_id = 20120345
email = hills@school.edu
name = Tommy Holness
phone = 5127438973
gender = M
student_id = 20120212
email = tommy@school.edu
name = Lee Kin Fong
phone = 864564456434
gender = F
student_id = 30245678
email = fong@school.edu
在线演示
现在花一些时间来理解代码。我向您展示的代码是使用 C++11 编写的。它演示了现代 C++ 的许多习语。
- 如何读取文件。逐行。
- 如何分割一条线,并填充一个字符串向量。
- 如何填充结构(具体问题)
希望有帮助。