Reputation: 935
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.
Upvotes: 0
Views: 2659
Reputation: 584
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);
Upvotes: 1
Reputation: 523
cin.getline (name,20);
cin.getline (address,50);
cin.getline (vehicle,10);
cin >> age;
Upvotes: 1