Search code examples
c++filefile-handlingdata-files

Getting unusual output in simple file handling program


What is the problem with this code? I am trying to write to a binary files MCQ type question e.g, Question: If a computer provides database services to other, then it will be known as ? 1.Web server 2.Application 3.Database server 4.FTP server

ID: 1

Answer: 3

.

.

.

But I am getting unusual output. Please have a look at the code I have provided comments. The program asks for questions and write it to a binary file. The id is automatically incremented, the question and the answer is asked from the user. If the question is "x" then the program stops and if its anything else it asks for the answer and set all three id, question, answer to a temporary object and then write it to the file.

The program work fine for the first question & answer and then directly asks for the answer for the second answer without asking for the second question.

#include <iostream>
#include <fstream>
#include<string.h>
#include<conio.h>


using namespace std;

class questions{    //start of class
                    //private members
int id; //identification number for question ( 1,2,3,....)
char ques[100]; //question
int ans;    //answer (1,2,3,4) MCQ
public: //public members

void displayques() //displays question
{
    cout<<ques; //the same
}
int getans()    //returns answer
{
    return ans; //the same

}

int getid() //returns id
{
    return id; //the same
}

void setques(char q[]) //set the given string in parameter to the question.
{
strcpy(ques,q);
}

void setid(int i) //set the given int as id
{
id=i;
}
void setans(int a) //set the given int as answer
{
ans=a;
}
};          //end of class questions

int main()  //start of main
{
    questions quesobj;  //create an object of class questions
ofstream quesfile;  //creates and object of class ofstream

quesfile.open("questions.dat",ios::out|ios::binary);    //opens questions.dar in output mode as binary with the object quesfile of ofstream


char ask='y';   //to stop the process when its changed to n
char tempques[100]; //to temporarily store the question
int tempid=1;   //to temporarily store the id, initially at 1, later is incremented
int tempans;    //to temporarily store the answer

while(ask!='n') //runs upto the the point when use wants to escape the loop
{


    cout<<"Question? or enter x to stop"<<endl; //asks the questions also ask if user want to escape can enter x
    gets(tempques); //gets the question in temporary variable
    cout<<"Question registered"<<endl;  //shows question is ready to be written
    if(strcmp(tempques,"x")==0)      //if user enter the question as x
    {
        ask='n'; //sets ask to n which will end the loop
    }
    else        //if user enters something else than x, it is considered the question
    {
            cout<<"Answer:"<<endl;  //ask for the answer
            cin>>tempans;   //stores answer in temporary variable
            cout<<"Answer registered"<<endl; //shows answer is ready to be written
            quesobj.setid(tempid);  //sets id to the temp object of the class questions
            quesobj.setques(tempques); //sets question to the temp object of the class questions
            quesobj.setans(tempans); //sets answer to the temp object of the class questions

       quesfile.write((char *)&quesobj, sizeof(quesobj));   //write the temp object of class questions to the binary file
       tempid++;   //tempid is incremented for the next loop so that every question has its own id

    }



} //end of while
quesfile.close();   // closes the file using the object of ofstream
}

OUTPUT:

Question? or enter x to stop
This is my first question?
Question registered
Answer:
2
Answer registered
Question? or enter x to stop
Question registered
Answer:
_

Solution

  • As suggested in the comments,


    you should not mix C and C++ style IO.
    As your code was not compiling on my system, I have cleaned your code a bit. I have tested it and its now working perfectly.

    #include <iostream>
    #include <sstream>
    #include <fstream>
    #include <string>
    
    using namespace std;
    
    
    int string_to_int(const string& str)
    {
        stringstream ss(str);
        int str_int;
        ss >> str_int;
        return str_int;
    }
    
    
    class Question
    {
        int id;
        string question_string;
        int answer;
    
    public:
    
        void displayQuestion()
        {
            cout << question_string;
        }
    
        int getAnswer()
        {
            return answer;
        }
    
        int getId()
        {
            return id;
        }
    
        void setQuestion ( const string& question_string_)
        {
            question_string = question_string_;
        }
    
        void setId ( int id_ )
        {
            id = id_;
        }
        void setAnswer ( int answer_ )
        {
            answer = answer_;
        }
    
    };
    
    
    int main()
    {
        Question question;
        ofstream question_file;
    
        question_file.open ( "questions.dat", ios::out | ios::binary );
    
        char option = 'y';
        string temp_question;
        int temp_id =1;
        int temp_answer;
    
        while ( option != 'n' )
        {
            cout << "Question? or enter 'x' to stop" << endl;
            getline(cin, temp_question);
            cout << "Question registered" << endl;
    
            if (temp_question == "x")
            {
                option = 'n';
            }
            else
            {
                cout << "Answer? :" << endl;
                string temp_answer_string;
                getline(cin, temp_answer_string);
                temp_answer = string_to_int(temp_answer_string);
                cout << "Answer registered" << endl;
    
                question.setId ( temp_id );
                question.setQuestion ( temp_question );
                question.setAnswer ( temp_answer );
    
                question_file.write ( ( char* ) &question, sizeof ( question ) );
                temp_id++;
            }
        }
    
        question_file.close();
    }