Hello. I've a problem here. I'm not sure why it doesn't work (I know it's pretty basic).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
int main()
{
int x;
std::cout << "Enter x: ";
std::cin >> x;
std::cout << x << std::endl;
char name[99];
std::cout << "Enter your name: ";
std::cin.get(name, 99);
std::cin.clear();
std::cin.ignore(1000, '\0');
std::cout << name;
//some other codes...
}
Okay, the problem here lies at .clear() and .ignore(). What happens is that "name" does not display. And the program continues to run forever. So when I changed to .ignore (1, '\0'), the program ends immediately after I input a 2nd enter, but still no display of "name".
Am I doing it wrong? I know that mixing cin >> and cin.get produces this problem. How do I go about solving it?
When you input the value of x and press enter the digits and a newline character are added to the input buffer. "17\n"
std::cin >> x; only reads the digits and leaves the newline character still in the input buffer. "\n"
std::cin.get(name, 99); reads until it finds a newline character. There is already a newline character in the input buffer so it will not wait for more input. This leaves the input buffer empty. ""
std::cin.ignore(1000, '\0'); will read until it finds a null character or up to 999 characters. So to get past this statement you will have to input a null character (which I have no idea if or how you can do) or input 999 characters. This is probably not what you want.
When you use operator>> and get (or getline) to read lines in the same program I think what you should do is that after you use operator>> you always make sure to remove the newline character at the end. You could place std::cin.ignore(); after each time you use operator>>, that will work as long as there are no extra characters between the value and the newline character. To be a bit more robust you can use something like std::cin.ignore(1000, '\n'); which will discard the whole rest of the line.