8.9 代码
#include <iostream>
#include <sstream>
using namespace std;
istream& in_out(istream &in)
{
int temp;
while (1) {
cin >> temp;
/* 到达文件结尾 */
if (in.eof()) {
cout << "EOF" << endl;
break;
}
/* 系统级错误 */
if (in.bad())
throw runtime_error("iostream error!");
/* 数据错误,清除错误标志,重新输入 */
if (in.fail()) {
cout << "format error, enter again: " << endl;
in.clear();
in.ignore(100, '\n');
continue;
}
cout << temp << endl;
}
return in;
}
int main(int argc, char *argv[])
{
istringstream text("This is a test line.");
in_out(text);
return 0;
}
8.10 代码:
#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
int main(int argc, char *argv[])
{
ifstream input(argv[1]);
string line;
vector<string> text;
while(getline(input, line)) {
text.push_back(line);
}
//输出验证
string word;
for (auto l : text) {
istringstream strm(l);
while(strm >> word)
cout << word << endl;
}
return 0;
}
8.11 代码:定义在外层,使用str()成员, sstream strm; strm.str(s):将string s拷贝至strm中,注意重复使用字符串流时,每次都要clear().
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
struct PersonInfo {
string name;
vector<string> phones;
};
int main(int argc, char *argv[])
{
string line, word;
vector<PersonInfo> people;
istringstream record;
while (getline(cin, line)) {
PersonInfo info;
record.clear();
record.str(line);
record >> info.name;
while(record >> word)
info.phones.push_back(word);
people.push_back(info);
}
return 0;
}
本文探讨了C++中流操作的高级应用,包括如何处理文件读取过程中的错误,利用istringstream进行字符串解析,以及如何使用istringstream和vector来解析并存储人员信息。通过实例展示了如何读取和解析复杂的数据结构。
33万+

被折叠的 条评论
为什么被折叠?



