读文件到string的vector(?)

// 按单词读有误,读出来的和按行读效果一致。
1
#include <iostream> 2 #include <fstream> 3 #include <string> 4 #include <vector> 5 6 using namespace std; 7 8 int fileToLineVector(const string fileName, vector<string> &svec) 9 { 10 // 创建ifstream对象inFile并绑定到由形参fileName指定的文件 11 ifstream inFile(fileName.c_str()); 12 if (!inFile) // 打开文件失败 13 { 14 return 1; 15 } 16 17 // 将文件内容读入到string类型的vector容器 18 // 每一行存储为该容器对象的一个元素 19 string s; 20 while (getline(inFile, s)) 21 { 22 svec.push_back(s); 23 } 24 inFile.close(); // 关闭文件 25 26 if (inFile.eof()) // 遇到文件结束符 27 { 28 return 4; 29 } 30 31 if (inFile.bad()) // 发生系统级故障 32 { 33 return 2; 34 } 35 36 if (inFile.fail()) // 读入数据失败 37 { 38 return 3; 39 } 40 41 return 0; 42 } 43 44 int fileToWordVector(const string fileName, vector<string>& svec) 45 { 46 // 创建ifstream对象inFile并绑定到由形参fileName指定的文件 47 ifstream inFile(fileName.c_str()); 48 if (!inFile) // 打开文件失败 49 { 50 return 1; 51 } 52 53 // 将文件内容读入到string类型的vector容器 54 // 每个单词存储为该容器对象的一个对象 55 string s; 56 while (inFile >> s) // 读入单词 57 { 58 svec.push_back(s); 59 } 60 inFile.close(); // 关闭文件 61 62 if (inFile.eof()) // 遇到文件结束符 63 { 64 return 4; 65 } 66 if (inFile.bad()) // 发生系统级故障 67 { 68 return 2; 69 } 70 if (inFile.fail()) // 读入数据失败 71 { 72 return 3; 73 } 74 75 return 0; 76 } 77 78 void showVector(vector<string> svec) 79 { 80 for (vector<string>::iterator iter = svec.begin(); iter != svec.end(); ++iter) 81 { 82 cout << *iter << endl; 83 } 84 } 85 86 void test() 87 { 88 string strFileName = "file.txt"; 89 // 文件按行读 90 cout << "文件按行读" << endl; 91 vector<string> lineVec; 92 fileToLineVector(strFileName, lineVec); 93 showVector(lineVec); 94 95 // 文件按单词读 96 cout << "文件按单词读" << endl; 97 vector<string> wordVec; 98 fileToLineVector(strFileName, wordVec); 99 showVector(wordVec); 100 101 } 102 103 int main() 104 { 105 test(); 106 return 0; 107 }

 

posted @ 2015-05-31 12:28  -学以致用-  阅读(863)  评论(0编辑  收藏  举报