编写程序,将来自文件中的行保存在一个vector<string>,然后使用一个istringstream 从vector中读取数据,每次读一个单词
#include<fstream> #include <vector> #include<string> #include<iostream> #include <sstream> #include <stdexcept> using namespace std; /*istream & f(istream&in){ string v; while (in>>v,!in.eof()) { if (in.bad()) throw runtime_error("IO流错误"); if (in.fail()){ cerr << "数据错误,请重试" << endl; in.clear(); in.ignore(100, '\0'); continue; } cout << v << endl; } in.clear(); return in; }*/ int main() { ifstream in("data.txt"); if (!in){ cerr << "无法打开文件" << endl; return -1; } string line; vector<string>words; while (getline(in, line)) words.push_back(line); in.close(); vector<string>::const_iterator it = words.begin(); while (it != words.end()){ istringstream line_str(*it); string word; while (line_str >> word) cout << word << " "; cout << endl; ++it; } system("pause"); return 0; }