1 #include <iostream> 2 #include <fstream> 3 #include <vector> 4 #include <string> 5 6 using namespace std; 7 8 ifstream& ReadLine(ifstream& in, vector<string> &vecLines) 9 { 10 string line; 11 while (!in.eof()) 12 { 13 getline(in, line); 14 cout<<line<<endl; 15 vecLines.push_back(line); 16 } 17 return in; 18 } 19 ifstream& ReadStr(ifstream& in, vector<string> &vecStrs) 20 { 21 string str; 22 while (!in.eof()) 23 { 24 in>>str; 25 cout<<str<<endl; 26 vecStrs.push_back(str); 27 } 28 return in; 29 } 30 int main() 31 { 32 ifstream inFile("1.txt"); 33 if (!inFile) 34 return -1; 35 vector<string> vecLines; 36 ReadLine(inFile,vecLines); 37 inFile.close(); 38 inFile.clear(); 39 inFile.open("1.txt"); 40 if (!inFile) 41 return -1; 42 vector<string> vecStrs; 43 ReadStr(inFile,vecStrs); 44 inFile.close(); 45 inFile.clear(); 46 return 0; 47 }
总结:
(1)ifstream使用getline获取文件内一行元素。
(2)ifstream继承istream可以使用>>获取单个字符串。
结果:
时间: 2024-11-04 22:57:11