从fstream读取数据 [英] Read data from fstream

查看:152
本文介绍了从fstream读取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从fstream读取数据,但是此代码不起作用. 它将0放入控制台. 你能帮我吗?

I'm trying to read data from a fstream but this code doesn't work. It puts 0 to the console. Can you help me?

// g++ -Wall main.cpp -o main.exe

#include <fstream>
#include <iostream>
#include <string>
#include <sstream>

int main()
{
    std::fstream file("main.txt", std::fstream::in | std::fstream::out | std::fstream::app);

    file << "45634w6\n";
    file << "dtusrjt\n";

    while (!file.eof())
    {
        std::string line;
        std::cout << std::getline(file, line) << "\n";
    }


    int a;
    std::cin >> a;
}

推荐答案

只需尝试以下代码,该代码即可为您提供帮助

Just try this code this code will help you

#include <fstream>
#include <iostream>
#include <string>
//#include <sstream>
using namespace std;
int main()
{
fstream file("main.txt");

file << "45634w6\n";
file << "dtusrjt\n";
file.close();
file.open("main.txt");
    string line;
while (!file.fail())
{
    getline(file, line);
    cout <<line  << "\n";
}


int a;
cin >> a;
}

这篇关于从fstream读取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆