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

C++ I/O库练习

时间:2017-04-08 00:36:40      阅读:235      评论:0      收藏:0      [点我收藏+]

标签:include   方法   bsp   创建   logs   names   打开文件   fst   iostream   

编写函数,以读模式打开一个文件,将其内容读入到一个string的vector中,将每一行作为一个独立的元素存于vector中,并输出。

思路:1.以读的模式打开文件“目录.txt”;

   2.先创建string对象line,使用getline()按行循环读取“目录.txt” in的内容存于line;

   3.要想把每一行内容存于vector对象words中,就要使用vectro容器的push_back()方法,即words.push_back(line);

   4.使用迭代器循环输出vector的元素word。

 

 1 #include<iostream>
 2 #include<fstream>
 3 #include<string>
 4 #include<vector>
 5 #include<sstream>
 6 
 7 using namespace std;
 8 
 9 int main()
10 {
11 ifstream in("..\\目录.txt");
12 if (!in)
13 {
14 cerr << "无法打开输入文件!" << endl;
15 return -1;
16 }
17 string line;
18 vector<string> words;
19 while (getline(in,line))
20 {
21 words.push_back(line);
22 }
23 in.close();
24 vector<string>::const_iterator it = words.begin();
25 
26 while (it != words.end())
27 {
28 istringstream line_str(*it);
29 string word;
30 while (line_str >> word)
31 cout << word << " ";
32 cout << endl;
33 ++it;
34 
35 }
36 return 0;
37 }

 

C++ I/O库练习

标签:include   方法   bsp   创建   logs   names   打开文件   fst   iostream   

原文地址:http://www.cnblogs.com/Burgess-Fan/p/6680445.html

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