0

I'm working on this code which is asking user to input data (student data).

I made a constructor which is taking input of all fields on first run which goes fine on the first run. When I continue to go again via loop its skipping the Name input every time.

Code

#include<iostream>
#include<fstream>
#include<string>

using namespace std;
class person{
private:
    string sName;
    string fName;
    string sAddress;
public:
    person(){
        cout << "Enter Details\n";
        cout << "Name :";
        getline(cin,sName);
        cout << "Father's Name :";
        getline(cin,fName);
        cout << "Address :";
        getline(cin,sAddress);
        cout << sName << fName << sAddress;
        
        ofstream myfiles("person.txt",ios::app);
        myfiles<<sName<<endl;
        myfiles<<fName<<endl;
        myfiles<<sAddress<<endl;
        myfiles.close();
        
        checkLoop();
    }
    
    void checkLoop(){
        int choice{};
        cout << "\nDo you want to continue?\n1)Continue\tx)Anything else for exit!"<<endl;
        cin >> choice;
        switch(choice){
            case 1:
                person();
                //break;
            default:
                break;
        }
    }
};
int main()
{
    person p1;
    return 0;
}

Output:

Do you want to continue?
1)Continue  x)Anything else for exit!
1
Enter Details
Name :Father's Name :

When I choose the first option Continue, it's skipping the "Name" part.

bijoy26
  • 133
  • 9
Sumit kumar
  • 402
  • 2
  • 10

1 Answers1

1

This is happening due to the fact that when you are reading choice using cin, then it will read the choice leaving the newline character behind.

That’s why when you try to read name by getline() it reads endofline character (Due to this in the person.txt you will see there will be blank spaces in name part).

So just use cin.ignore() after cin>>choice;

adrsh23
  • 210
  • 2
  • 10
  • 1
    thanks this solution worked curious how little i know about cin functions i have to read more about it. thank you – Sumit kumar Jun 06 '21 at 08:36
  • 1
    @Sumitkumar check [this answer](https://stackoverflow.com/a/21567292/8568965) for a bit more insight about this special case. – bijoy26 Jun 06 '21 at 08:48
  • 1
    @Sumitkumar when I it encountered it previously I had the same reaction as yours : ) – adrsh23 Jun 06 '21 at 08:56