文件头
#include <iostream>#include <fstream>#include <string>#include <vector>#include <sstream>
using namespace std;
从文件中逐词读取
void getFromFile() {
ifstream fin("C:\\data.txt");
string s;
while (fin >> s)
{
cout << "Read from file:" << s << endl;
}
}
从文件中逐行读取
void getFromFileByLine() {
ifstream fin("C:\\data.txt");
string s;
while (getline(fin, s))
{
cout << "Read from file:" << s << endl;
}
}
从文件中逐词读取并写入vector容器中
void fileToVectorByWord() {
ifstream infile;
infile.open("C:\\data.txt");
if (!infile) { //加入异常判断
cout << "error : cannot open the file" << endl;
}
vector<string> v;
string s;
while (!infile.eof()) {
infile >> s;
v.push_back(s);
}
vector<string>::const_iterator it = v.begin(); //开始验证
while (it != v.end()) {
cout << *it << endl;
++it;
}
}
从文件中逐行读取并写入vector容器中
void fileToVectorByLine() {
ifstream infile;
infile.open("C:\\data.txt");
if (!infile) {
cout << "error : cannot open the file" << endl;
}
vector<string> v;
string s;
while (! infile.eof()) {
getline(infile, s);
v.push_back(s);
}
vector<string>::const_iterator it = v.begin();
while (it != v.end()) {
cout << *it << endl;
++it;
}
}
istringstream的使用
void testStringstream()
{
string line;
string word;
while (getline(cin, line)) { //从控制台获取一行字符
istringstream stream(line); //将line绑定成istringstream
while (stream >> word) { //逐词输出
cout << word << endl;
}
}
}