I'm building an application to teach myself C++. I'm currently in the "fix areas where users could screw up the program" phase.
What I've noticed is that with something like:
int x = 0;
cout << "Enter an integer: "; cin >> x;
It's easy enough to have to fix the input stream if the user enters something like 'w' or another non-integer.
What I can't figure out, though, is how I can get around what occurs if the user mistakenly presses enter while not having entered any data. Usually the cursor just moves down the screen until something other than enter is input.
So the question is: if the user hits enter in a scenario like the above, but nothing else, how can I have another prompt that says something like: "Invalid entry. Try again: " type thing?
I think you're going to have to use std::getline() for that, and I believe it only reads in strings so you'll have to convert anything you get from it to whatever data type you need it to be.
I dont think there is any better way than std::getline().
On similar lines, Is there any way we can move the cursor back to orignal position?
If this is possible portably I think it is better to do this instead of showing up an error message.
In CornedBee's subconscience, he realized that the ascii code for backspace is 8, and therefore typed the 8th letter of the alphabet, "h", instead of "b"
There is no C/C++ standard way of doing what you want - but there are solutions:
For *nix type systems there are libraries like curses and ncurses which allow you to manipulate the cursor posistion amoung other things.
For Windows systems there are Win32 API functions for maninpulating the console. Here is a good tutorial for the Windows side of things.
There was a question sometime in the past couple of days asking for the C++ equialent to _getch(). I don't know if it was this forum or the Win API forum but I doubt it was in the other forum. An answer was provided that uses a platform-specific functions to set up the console for unbuffered input and probably all platforms have a way to do that, in case that helps.
Bookmarks