码迷,mamicode.com
首页 > 编程语言 > 详细

C++ Primer 习题8.9 ifstream使用方法

时间:2015-02-14 21:23:19      阅读:288      评论:0      收藏:0      [点我收藏+]

标签:

 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可以使用>>获取单个字符串。

结果:

技术分享

C++ Primer 习题8.9 ifstream使用方法

标签:

原文地址:http://www.cnblogs.com/gis-flying/p/4292145.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!