How to read string, char , int all from one file untill find eof in c++?
c++, eof, file
Solution
A number of things:
- eof checking isn't appropriate (most of the time). Instead, check stream state
- don't use `read` as it won't skip whitespace
- after your timelimit, ignore input until the end of the line
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ifstream infile ("indata.txt");
std::string t_ques;
char t_ans;
int t_time_limit;
std::getline(infile, t_ques);
while (infile >> t_ans >> t_time_limit)
{
cout << t_ques << endl;
cout << t_ans << endl;
cout << t_time_limit << endl;
infile.ignore();
std::getline(infile, t_ques);
}
}
See it live on Coliru
Problem
What's wrong with my code? I want to get intput from file (first one string, then a char , then int). I want it for whole file. Here is my code. This is giving me so pain. What can i do? Please help me. ``` //file handling //input from text file //xplosive #include<iostream> #include<fstream> using namespace std; ifstream infile ("indata.txt"); int main() { const int l=50; //string t_ques; char t_ques[l]; char t_ans; int t_time_limit; while(!infile.eof()) //while(infile) { infile.getline(t_ques,l); //infile >> t_ans ; infile.get(t_ans); infile >> t_time_limit; cout << t_ques << endl; cout << t_ans << endl; cout << t_time_limit << endl; } return 0; } ``` my indata.txt file contain ``` what is my name q1? t 5 what is my name q2? f 3 what is my name q3? t 4 what is my name q4? f 8 out put should be the same. but my while loop don't terminate. ```