cin's input buffer

A

aegis

Consider the following:

#include <iostream>
#include <string>

using namespace std;

int main(void)
{
int a, b, c;
cin >> a; cin >> b; cin >> c;
string s;
getline(cin, s);
return 0;
}

is there a newline hanging around cin's input buffer
for getline to accept and return immediately?

Because that is how the programming is behaving.
 
A

Alf P. Steinbach

* aegis:
Consider the following:

#include <iostream>
#include <string>

using namespace std;

int main(void)
{
int a, b, c;
cin >> a; cin >> b; cin >> c;
string s;
getline(cin, s);
return 0;
}

is there a newline hanging around cin's input buffer
for getline to accept and return immediately?

Yes.

However, 'getline' consumes a newline.


Cheers & hth.,

- Alf
 
J

James Kanze

Consider the following:
#include <iostream>
#include <string>
using namespace std;
int main(void)
{
int a, b, c;
cin >> a; cin >> b; cin >> c;
string s;
getline(cin, s);
return 0;
}
is there a newline hanging around cin's input buffer
for getline to accept and return immediately?

Probably. If you're reading from a console, most systems won't
pass the program anything until there is a new line, so the code
can't read the value for c until a new line is entered following
it. And of course, reading an int doesn't remove that new line.

The function getline doesn't necessarily look for a new line of
text; it can't know that you've already read characters from the
current line, so it simply reads from where you are up to (and
including) the next new line character.
 
A

aegis

Probably.  If you're reading from a console, most systems won't
pass the program anything until there is a new line, so the code
can't read the value for c until a new line is entered following
it.  And of course, reading an int doesn't remove that new line.

The function getline doesn't necessarily look for a new line of
text; it can't know that you've already read characters from the
current line, so it simply reads from where you are up to (and
including) the next new line character.

Is there a preferred/standard way of discarding cin's input buffer?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,566
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top