Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read string, char , int all from one file untill find eof in c++?

Tags:

c++

file

eof

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.
like image 469
Xplosive Avatar asked Jan 30 '26 10:01

Xplosive


1 Answers

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

like image 112
sehe Avatar answered Feb 02 '26 02:02

sehe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!