0

I want to do a program where I key in the a question and answer to a text file with unique id(auto increment number). Currently the program only works if the text file is empty, once I have written something in the text file, the next time I run it, it does not show any output. Just blank CMD

#include<fstream>
#include<stdlib.h>
#include<string.h>

using namespace std;

class stud
{
    public:
        string answers, questions;
        float score, totalScore;
        int rollno;
        
        stud()
        {
            rollno=0;
        }
        
        int get_no();
        void getdata();
};

int stud::get_no()
{
    ifstream outfile("questions.txt",ios::in);
    int quizID;
     
    while(!outfile.eof())
    {
        outfile>>rollno;
        outfile>>questions;
        outfile>>answers;
        if(outfile.eof())
        {
            break;
        }
    }
    
    quizID = rollno;
    quizID = quizID + 1;
    
    outfile.close();
    
    return quizID;
}

void stud::getdata()
{
    ofstream outfile("questions.txt", ios::out|ios::app);
    
    rollno = get_no();
    
    cout<<"Add New Question\n";
    getline(cin,questions);
    cout<<"Add New Answers\n";
    getline(cin,answers);
    
    outfile<<"ID "<<rollno<<": Question : "<<questions<<" Answer : "<<answers<<"\n";
    outfile.close();
    
}

int main()
{
    stud s1;
    s1.getdata();
    return 0;
}
J R
  • 1
  • 1
    Did you try to debug the code? – Quimby Jan 13 '22 at 13:20
  • You should [edit] and show a minimal "questions.txt" file – Jabberwocky Jan 13 '22 at 13:22
  • My guess would be that `getdata` locks `questions.txt` which then causes `outfile` in `get_no` to fail to open and therefore `outfile.eof()` is never true – Alan Birtles Jan 13 '22 at 13:23
  • 4
    You're trying to read the string "ID" into an `int`, which fails and puts the stream in an error state, and `eof()` never becomes true. Read [Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons). And write your file in a structure that's easy to write reading code for. – molbdnilo Jan 13 '22 at 13:29

0 Answers0