Read data from fstream

2020-05-05 17:29发布

问题:

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


标签: fstream