input error!

Hello to everyone!
I isolated the proble in the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include<iostream>
#include<string>
using namespace std;
struct dadospessoais{
	int status;
	string a;
	string b;
} agenda[20];	
int main(void){
	int option;
	int pos=0;
	cout<<"option label: ";
	cin>>option;
	cout<<"header text: "<<pos<<endl;
	cout<<"label 01: ";
	getline(cin, agenda[pos].a);
	cout<<"label 02: ";
	getline(cin, agenda[pos].b);
	return 0;
}



And that is ... it skips agenda[pos].a input?!

This is the output:

option label:3
header text: 0
label 01: label 02:

What is missing?

Thansk
closed account (z05DSL3A)
Try 'cin.ignore();' after cin>>option;

cin>>option; will leave a 'return' in the stream that the first getline will pickup as a line of text.
Last edited on
It works with ...
cin.ignore();
... and also with ...
getchar();
... but still looking for the "why?" :)

What is the alternative for cin>>option; to avoid this problem?
Thanks again.
closed account (z05DSL3A)
Generally speaking

The why, when you call cin>>option;, the user types in a number into the stream and then presses return, so the stream has something like '123\n' in it. The number part of the stream is taken out and put in ‘option’, leaving the '\n' in the stream.

Getline will read the contents of the stream up to the first '\n', as there is one in the stream already it immediately returns from the call with an empty string.

cin.ignore() flushes the contents of the stream, and getchar(); will remove the single ‘\n’ from the stream.

Dose that make sense?
Yes it does :)
I will take a deeper look at the streaming chapter for details.
Over and out ;)
Another possibility is to use a combination of cin.sync() and cin.clear(), in that order. istream::sync discards all contents of the input buffer, and ios::clear clears the error bits (badbit, failbit and eofbit).

Note that istream::sync returns different values for different input streams, so be aware of the difference between buffered and unbuffered streams. In practice, unbuffered streams connected to cin aren't common in desktop computers and notebooks. There is also a chance of error with both functions, so take note of that too.
Topic archived. No new replies allowed.