Originally Posted by
PersianStyle
I also have another minor question if anyone would like to help
I was going along with the tutorial and it tells me to put cin.ignore(); after having the user input a value and to also have cin.get(); at the end of the program so i can see the results of the program. Could someone explain this a little bit more for me please. I mean I kinda understand how the cin.ignore(); removes the enter and the cin.get(); waits for the user to press enter, but its still kinda bothering me, I don't really get it.
operator>> performs formatted input. That is, it interprets the data read in context of its right-hand operand. It skips over and discards whitespaces and stops at newline but leaves it in the input buffer where it [newline] waits to be read. The next read from input buffer with operator>> will discard the newline left in there, but other member functions of cin that perform unformatted input will read it, resulting in unexpected behavior.
Try:
Code:
#include <iostream>
int main(int argc, char** argv)
{
char name[256];
int age;
std::cout << "Enter your age: ";
std::cin >> age;
std::cout << "Enter your name: ";
std::cin.getline(name, 256); //default delimiter is '\n', so this will result in a null string
std::cout << "Your name is " << name << ", your age is "
<< age << ".\n";
return 0;
}
Adding std::cin.ignore() after std::cin >> age; will read and discard the next character from the input buffer, '\n' in this case, getline() will have nothing to read and will wait for input from user.
I personally prefer std::cin.sync(), but that might have side-effects I'm not aware of - I'm but a newbie myself, and if just said something incredibly stupid I expect someone to come along and smack me around.