reading from stdin

Hi

I want to read a string of unknown length from stdin. I tried to follow the approach from this link.

http://www.cplusplus.com/reference/string/string/getline/

My code is like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <string>

using namespace std;

int n;
cin >> n;
cout << "The value of n is " << n << endl;
    
string str;
getline(cin, str);
    
cout << "The entereed string is " << str << endl;



What I have noticed is that if I take integer input from cin (cin >> n;) in the above code before getline, the control does not stop on getline to take str as input from the console. If I don't do (cin >> n) before getline then the control stops on getline and takes the string as input.

Can someone please explain this behavior?

What is the best way to read from console multiple strings of unknown length in combination with the integers?
Can someone please explain this behavior?

This is because the extraction operator delimits on white space, such as the return carriage, but it does not remove it from the buffer. The function "getline()" also delimits on white space by default, so it sees the return carriage in the buffer and does what it is supposed to. Either flush your input with 'std::cin.ignore()' or just use 'getline()' since it extracts the white space.

Thanks "Computergeek" and MiniPaa for the insights.
Three college professors were driving down the highway at a very slow speed. A policeman pulled them over and explained that driving so slowly on the highway could be hazardous. The driver pointed out the sign that read "20." He explained that he was going 20 mph because of the sign.




-----------------------------------------------------------------------------
http://www.fifa15online.com/
http://www.eafifa15.com/
...The policeman pointed out that the sign indicated they were driving on Highway 20.
Somewhat embarrassed the professor apologized and promised to be more observant.
As the policeman turn to walk back to his car, he noticed the other two professors on the floor ...looking scared to death! He asked the driver, "What's wrong with them?"
The driver replied, "We just turned off Highway 105.
http://www.ajokeaday.com/Clasificacion.asp?ID=17#ixzz3Fne8TlUV

Is there a reason you are derailing this thread?
Topic archived. No new replies allowed.