Empty string after cin >>

First I ask the user if he wants a method or another (1 or 2)

After processing that I start reading lines with getline to store them in a string vector, but the first line I read is " " (I guess it is because of the cin >> I use at the beginning). The only solution I found is to put an extra getline(cin, s);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  cout << "Do you want to vertical (1) or horizontal (2) concatenation? ";

	int success = 0;
	int choice = 0;

	while (success == 0) {
		cin >> choice;
		if (choice == 1 || choice == 2)
			success = 1;
	}

	cout << "Insert words to create paragraph: " << endl;

	vector<string> paragraph;
	string s;

	//to avoid an empty string
	getline(cin, s);

	while (getline(cin, s)) {
		paragraph.push_back(s);
	}


Is there a better way?
Last edited on
Getline is non-formatted input.
cin is formatted input.

The trick is to remember that all user input ends with an ENTER.

1
2
3
4
5
6
7
8
while (using formatted input)
{
  cin >> stuff;
}
cin.ignore( numeric_limits<streamsize>::max(), '\n' );

// now use unformatted input
getline( cin, s );

Hope this helps.
Thanks!
Since the problem is quite common, you can find a lot more about it on line.
For example:
http://en.cppreference.com/w/cpp/string/basic_string/getline
When used immediately after whitespace-delimited input, e.g. after int n; std::cin >> n;, getline consumes the endline character left on the input stream by operator>>, and returns immediately. A common solution is to ignore all leftover characters on the line of input with cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); before switching to line-oriented input.

http://augustcouncil.com/~tgibson/tutorial/iotips.html#problems
...The solution is to add std::cin.ignore(); immediately after the first std::cin statement. This will grab a character off of the input buffer (in this case, newline) and discard it...

http://www.cplusplus.com/forum/articles/6046/
...Cin is notorious at causing input issues because it doesn't remove the newline character from the stream or do type-checking...

...And many others.
Topic archived. No new replies allowed.