美文网首页
c++练习文件输入和流的逐行输入

c++练习文件输入和流的逐行输入

作者: 科学旅行者 | 来源:发表于2016-11-26 20:44 被阅读7次

参考资料:《C++ Primer习题集(第5版)》

#include <iostream>
#include <fstream>//与文件相关的标准库;
#include <string>
#include <vector>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    ifstream in("data.txt");//打开文件;//以读模式打开一个文件;
    if (!in) {
        cerr << "无法打开输入文件" << endl;
        return -1;
    }

    string line;
    vector<string> words;
    while (getline(in, line)) {//从文件中读取一行;
        words.push_back(line);//添加到vector中;
    }
    in.close();//输入完毕, 关闭文件;
    
    for (auto e : words) {//范围for语句, 遍历vector;
        cout << e << endl;//输出vector中的元素;
    }
    return 0;
}

相关文章

网友评论

      本文标题:c++练习文件输入和流的逐行输入

      本文链接:https://www.haomeiwen.com/subject/cuygpttx.html