0

In the following code, I have made two classes, the second class is inherited from the first one. However when I call the getdata function. it skips input, I have tried using cin.ingnore() and also cin>>ws, but I am still getting the same errors. It runs properly till " Enter the Last name" but after that, it just prints all the other things without taking the input.

#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;

class RegistrationModule{
    protected:
        string Firstname;
        string Lastname;
        double cnic;
        double contact;
        string address;
        static double challanno;
        
        public:
            RegistrationModule(){
                Firstname = "";
                Lastname = "";
                cnic=0;
                address = "";
                contact=0;
                challanno++;
            }
};
double RegistrationModule::challanno=105487;
class monthlyentry : public RegistrationModule{
    public:
        void getdata(){
            cout<<"Enter First Name"<<endl;
            getline(cin,Firstname);
            cin.ignore();
            cout<<"Enter Last Name"<<endl;
            getline(cin,Lastname);
            cin.ignore();
            cout<<"Enter your CNIC: "<<endl;
            cin>>cnic;
            cin.ignore();
            cout<<"Enter your Address: "<<endl;
            getline(cin,address);
            cout<<"Enter your contact number: "<<endl;
            cin>>contact;
            cout<<"Your Challan Number is: "<<challanno<<endl;
        }
};

int main(){
    int size;
    monthlyentry a;
    a.getdata(); 
}

1 Answers1

1

You cannot just slap ignore() randomly and expect things to work. By default, ignore() will remove 1 character. If there is no character there, it will set eof() bit and your stream cannot read anything more until you clear() eof flag from it.

Only use ignore() when there is a leftover end of line (like after formatted extraction).

    void getdata(){
        cout<<"Enter First Name"<<endl;
        getline(cin,Firstname);

        cout<<"Enter Last Name"<<endl;
        getline(cin,Lastname);

        cout<<"Enter your CNIC: "<<endl;
        cin>>cnic;
        cin.ignore();

        cout<<"Enter your Address: "<<endl;
        getline(cin,address);

        cout<<"Enter your contact number: "<<endl;
        cin>>contact;
        cin.ignore(); // might want to clear up before next extractions

        cout<<"Your Challan Number is: "<<challanno<<endl;
    }

To use std::ws, you would need to use directly in getline calls

std::getline(std::cin >> std::ws, Firstname);
Yksisarvinen
  • 18,008
  • 2
  • 24
  • 52