getline

S

slurper

what's wrong with this program:

#include <iostream>
#include <string>
using namespace std;

int main()
{
string string1, string2;

cout << "Type a word: ";
cin >> string1;
cout << "You typed: " << string1 << endl;

cout << "now type a line: ";
getline( cin, string2 ); <-------- doesn't wait for me here
cout << "you typed: " << string2 << endl;

return 0;
}

it compiles but when run it doesn't wait for me to enter a sentence at the
getline command

output:
Type a word: lol
You typed: lol
now type a line: you typed:

platform: mandrake linux using g++ on i386
 
R

Rob Williscroft

slurper wrote in in
comp.lang.c++:
what's wrong with this program:

#include <iostream>
#include <string>
using namespace std;

int main()
{
string string1, string2;

cout << "Type a word: ";
cin >> string1;

this reads in "lol" but *not* the final '\n'.
cout << "You typed: " << string1 << endl;

cout << "now type a line: ";
getline( cin, string2 ); <-------- doesn't wait for

this reads in the '\n' that wasn't read above.
me here cout << "you typed: " << string2 << endl;

return 0;
}

it compiles but when run it doesn't wait for me to enter a sentence at
the getline command

output:
Type a word: lol
You typed: lol
now type a line: you typed:

platform: mandrake linux using g++ on i386
Standatd C++.

I suggest you use getline for both inputs, always do this when
reading from the "console" as its line buffered anyway.

Use the exctactors (>>) for stringstream's, and files that
has been writen by programmes (other than notepad/emacs/vi/ed).

Rob.
 
J

John Harrison

slurper said:
what's wrong with this program:

#include <iostream>
#include <string>
using namespace std;

int main()
{
string string1, string2;

cout << "Type a word: ";
cin >> string1;
cout << "You typed: " << string1 << endl;

cout << "now type a line: ";
getline( cin, string2 ); <-------- doesn't wait for me here
cout << "you typed: " << string2 << endl;

return 0;
}

it compiles but when run it doesn't wait for me to enter a sentence at the
getline command

output:
Type a word: lol
You typed: lol
now type a line: you typed:

platform: mandrake linux using g++ on i386

cin >> string1 does not read a newline.
getline reads the newline that follows lol, therefore it doesn't wait.

Try typing "hello world" at the first prompt to see this more clearly.

john
 

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

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top