0

I have a simple structure which stores details of a person whose values needs to be initialized through user input. The structure is as follows :

typedef struct {

        char name[20];
        int age;
        char address[50];
        char vehicle[10];
}Runner;

I am using cin to store the value of each Runner but wish to take the inputs (that may contain whitespace in between) using enter key after each value entered.

Below is the code :

Runner run1;

        cout << "Enter name age address vehicle (pressing enter at each instance)" << endl;
        cin >> run1.name >> run1.age >> run1.address >> run1.vehicle ;

It is quite evident that space separated values would be considered as two unique entries.

How do I skip the white-spaces and cin only after enter is pressed. Also if there is another approach to such situations, it would be great to know the same.

Ashish K
  • 905
  • 10
  • 27

2 Answers2

1
cin.getline (name,20);
cin.getline (address,50);
cin.getline (vehicle,10);
cin >> age;
ShahzadIftikhar
  • 515
  • 2
  • 11
1

As the input may have whitespaces between them, you should use getline function.

cin.getline(run1.name,20);
cin.getline(run1.address,50);
cin.getline(run1.vehicle,10);
cin >> age

But if you want to take the value of age after taking the value of name, then you'll have to do something like this.

cin.getline(run1.name,20);
cin >> run1.age;
cin.getline(dummy,5);    //cin leaves a newline at the buffer. This line of code takes the newline from the buffer.
cin.getline(run1.address,50);
cin.getline(run1.vehicle,10);
  • Could you please explain more about the `dummy` thing that you have used in your code? – Ashish K Apr 21 '17 at 08:31
  • 1
    Yes. cin takes the input from the console. But leaves a newline '\n' in the buffer. And getline reads from the buffer untill a newline character has been found. So when you use getline immediately after a cin, the first cin leaves a newline and then the getline reads till the newline(so basically, getline reads an empty string). So if you delete the line cin.getline(dummy,5), the run1.adress will hold a empty string. So to remove the newline from the buffer, dummy takes the newline character, and run1.address had correct value. – Redwanul Haque Sourave Apr 21 '17 at 08:39
  • For more read this question: http://stackoverflow.com/questions/5739937/using-getlinecin-s-after-cin And the comment of Loki Askari – Redwanul Haque Sourave Apr 21 '17 at 08:40