cin << name << endl; cout >> "my name is " << name << endl;
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
std::cin.getline
or
std::cin >> smth;
+ std::cin.ignore();