问题
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