IO库的举例

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

using namespace std;

int fileToVector(string fileName, vector<string>& svec)
{
	ifstream inFile(fileName.c_str());
	if (!inFile)
		return 1;

	string s;
	//while (getline(inFile, s)) // 一次输入一行,
	//	svec.push_back(s); // 一次输入一行,
	 while(inFile >> s)  // 一次输入一个单词,
	svec.push_back(s);   // 一次输入一个单词,

	inFile.close();
	if (inFile.eof())
		return 4;
	if (inFile.bad())
		return 2;
	if (inFile.fail())
		return 3;
}

int main()
{
	cout << "ok? " << endl;

	vector<string> svec;
	string fileName, s;

	cout << "Enter fileName: ";
	cin >> fileName;

	switch (fileToVector(fileName, svec))
	{
	case 1:
		cout << "error: can not open file. " << fileName << endl;
		return -1;
	case 2:
		cout << "error: system failure. " << endl;
		return -1;
	case 3:
		cout << "error: read failure. " << endl;
		return -1;
	}

	cout << "向量里的内容:" << endl;
	for (vector<string>::iterator iter = svec.begin();
		iter != svec.end(); ++iter)
		cout << *iter << endl;

	cout << "文件有多少行:" << svec.size() << endl;

	return 0;
}

你可能感兴趣的:(IO库的举例)