3

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.
4
  • 3
    What input do you provide? What output do you get?
    – simonc
    Aug 22, 2013 at 21:13
  • 2
    could give some sample input, that is a sample content of input file. Aug 22, 2013 at 21:15
  • 1
    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
    – Xplosive
    Aug 22, 2013 at 21:18
  • @Xplosive It'd be easier to understand the file content plus output you receive if you edit your question rather than posting them as a comment
    – simonc
    Aug 22, 2013 at 21:19

2 Answers 2

3

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

0
0

Try to use this expression:

infile.open("indata.txt", ios::in);
// ...same loop...
infile >> t_ques >> t_ans >> t_time_limit;

// At the end close the file
infile.close();
1
  • won't parse the whole question
    – sehe
    Aug 22, 2013 at 21:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.