Alright, I've been having a weird experience with std::cin - hope someone can clarify things for me. std::cin doesn't accept white space as part of the input. However, this can sometimes cause problems since if you type 2 words, then the second word will be used as the input of the next std::cin input. Up to here, this is fine. However, under what circumstances will std::cin also use '\n' as input for the next std::cin? For example :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
double x;
double y;
char z;
int main()
{
std::cout << "Type In Equation: ";
std::cin >> x;
std::cin >> z;
if (z == '!') // To Skip Getting A "y" Value For Factorials
{
goto Operation;
}
std::cin >> y;
|
(This is code taken from a calculator I made) - No matter how much white space I put between x/z/y - the program has no trouble differentiating between these different values.
However, for this code :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
int main()
{
std::cout << "Pick 1 or 2: ";
int choice;
std::cin >> choice;
std::cin.ignore(32767, '\n'); // Code Won't Work Without This Line
std::cout << "Now enter your name: ";
std::string name;
std::getline(std::cin, name);
std::cout << "Hello, " << name << ", you picked " << choice << '\n';
return 0;
}
|
For this code, without std::cin.ignore(32767, '\n');, it wont work. Apparently, in this instance, when putting a number in for std::cin >> choice; - it'll also take '\n' as an input (which I assume is the space created when pressing enter). Since it's taken as an input, it's put into the next std::cin that's asking for a name.
So now, how come it's perfectly fine to have as much white space as you want (or pressing enter as many times as you want) in the first example without it being taken as an input - yet in the second one it is taken as an input and doesn't work as it was expected to without that extra line of code? Thanks.