Read data from fstream

孤人 提交于 2019-12-20 07:22:44

问题


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;
}

回答1:


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;
}


来源:https://stackoverflow.com/questions/24607385/read-data-from-fstream

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!