本次示例所使用文件为phonebook.txt文件,该文件记录了一些人的名字以及电话,文件格式如下(每一行为一条记录,以人名开始,后面跟随一个或多个电话):
james 15523951231 13212304212
jardon 14240324832
kebo 13424596304 15321340234 14920471921
任务需求:同时使用ifstream、istringstream将phonebook.txt中每条记录都读取到vector<struct>中,struct包含人名信息与电话信息。
代码示例如下:
.h文件:
#pragma once
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
struct PersonInfo
{
string name;
vector<string> phone;
};
vector<PersonInfo> getfileline(const string& txtstr);
.cpp文件:
# include "function.h"
vector<PersonInfo> getfileline(const string& txtstr) {
ifstream infile(txtstr, ifstream::in);
vector<PersonInfo> people;
if (infile.is_open())
{
string line;
int linenums = 0;
while (getline(infile, line)) {
cout << "line:" << line << endl;
++linenums;
PersonInfo info;
string phonewords;
istringstream instring(line);
instring >> info.name;
while (instring >> phonewords) {
info.phone.push_back(phonewords);
cout << "linenums:" << linenums << " name: " << info.name << " phone: " << info.phone.back() << "" << endl;
}
people.push_back(info);
}
infile.close();
}
else
cerr << "input of file is error!" << endl;
return people;
}
mian.cpp文件:
#include "function.h"
int main() {
getfileline("iotest.txt");
return 0;
}