cin << name << endl; cout >> "my name is " << name << endl;
Asked
Active
Viewed 43 times
-1
-
1`if (ans == "Yes" || ans == "yes") return getchoice2();` -- Look at your code carefully -- you are returning an `int` (the choice) from a function that returns a `double`. In addition, you are recursively calling `getmusclemass()` instead of using the proper looping constructs. Your `getmusclemass()` function should not be doing any input or output -- its job should be to accept values as parameters, and returns a value based on calculations, not I/O. As a matter of fact, maybe you should learn what function parameters are, since your program lacks any use of them. – PaulMcKenzie Aug 15 '17 at 20:52
1 Answers
0
Problem
When you say cin >> smth
, you want to get precisely smth, nothing more. End-line marker is not part of it, so it's not consumed. Unless you would have a special type for line, but there is no such thing in standard library.
When you use getline
you say you want to get a line. A line is string that ends with \n
, the ending is integral part of it.
So the problem is that std::cin
leaves an end-line \n
character in buffer.
Example
std::cin >> smth;
+---+---+---+---+---+----+
|'H'|'e'|'l'|'l'|'o'|'\n'| // In smth will be "Hello"
+---+---+---+---+---+----+
+----+
|'\n'| // But new-line character stays in buffer
+----+
std::cin >> smth2; // Its same like you would press just an 'enter', so smth2 is empty
Solution
- Use
std::cin.getline
or
- Use
std::cin >> smth;
+std::cin.ignore();

kocica
- 6,412
- 2
- 14
- 35
-
No, all the standard `operator>>` will skip whitespace before reading into a variable. That will consume the `'\n'` left in the buffer. It is only if you mix `>>` and `getline` that you might get an empty line. – Bo Persson Aug 15 '17 at 21:56