zoukankan      html  css  js  c++  java
  • C++ I/O库练习

    编写函数,以读模式打开一个文件,将其内容读入到一个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++ primer plus 第六章 课后题答案
    动态创建easyui控件的渲染问题
    晨报
    动态构建easyUI grid
    早起
    周末
    js ajax方式拼接参数
    5个月
    锻炼
    东湖夜色
  • 原文地址:https://www.cnblogs.com/Burgess-Fan/p/6680445.html
Copyright © 2011-2022 走看看