I was learning from https://www.learncpp.com/cpp-tutorial/an-introduction-to-stdstring/ and a question arises from the below code
#include <string>
#include <iostream>
int main()
{
std::cout << "Pick 1 or 2: ";
int choice{};
std::cin >> choice;
std::cout << "Now enter your name: ";
std::string name{};
std::getline(std::cin, name); // note: no std::ws here
std::cout << "Hello, " << name << ", you picked " << choice << '\n';
return 0;
}
the question arising line is
std::getline(std::cin, name); // note: no std::ws here
here above code accepts '\n' as input for std::cin ok!
And the output is below
Pick 1 or 2: 2
Now enter your name: Hello, , you picked 2
Simple!
so my question is why the output does not go in the next line after 'Hello,' because std::cin takes the value "\n"?
the problem is not to buffer! I want to say that the output must print
Pick 1 or 2: 2
Now enter your name: Hello,
, you picked 2
CodePudding user response:
From the documentation for std::getline():
getline reads characters from an input stream and places them into a string:
1) Behaves as UnformattedInputFunction, except that input.gcount() is not affected. After constructing and checking the sentry object, performs the following:
1) Calls str.erase()
2) Extracts characters from input and appends them to str until one of the following occurs (checked in the order listed)
a) end-of-file condition on input, in which case, getline sets eofbit.
b) the next available input character is delim, as tested by Traits::eq(c, delim), in which case the delimiter character is extracted from input, but is not appended to str.
c) str.max_size() characters have been stored, in which case getline sets failbit and returns.
Presumably you are running up against condition (b) above -- the newline character is recognized as a delimiter, "in which case the delimiter character is extracted from input, but is not appended to str"
(if you wanted to, you could do a std::cout << name.size() << '\n'; to see how many characters are in your name string... I suspect you will see that there are zero, since when you just press enter, there are zero characters present before the newline/delimiter character)
CodePudding user response:
because there is still a \n in the input buffer from the first read of choice, you need to tell cin to ignore it.
int choice{};
std::cin >> choice;
std::cin.ignore(); <<<=============
std::cout << "Now enter your name: ";
std::string name{};
EDIT
you wonder why name isnt equal to "\n" instead of ""
the reason is that getline ignores \n. it returns everything upto \n but not including the \n. So when the input buffer just has \n in it getline returns an empty string into name
