问题
My app reads user input using std::cin
stream.
In one place I would like to provide default input and let the user to accept it as it is (by pressing enter) or modify it before continuing (by removing old characters with backspace and adding new text).
I'm aware that characters can be placed directly into cin.rdbuf
, but that's not exactly what I want to achieve.
I would like to put characters into console window in the place where console's cursor is when waiting for user input and do no read them before user will accept them. User should be also able to remove them and write their own text.
Can something like this be achieve using cin
or do I have to simulate this by reading single characters and repainting content of the console?
回答1:
No, something like that cannot be done with std::cin
. Its read buffer is read directly from standard input. Standard input is a "cooked" character stream. All the editing is handled entirely by your operating system's terminal console, and pressing Enter
results in your application's std::cin
reading the entered text.
The traditional way this is done is to simply indicate the default input value in the prompt itself, and use the default value in the event of empty input, something like:
std::string buffer;
std::cout << "What color is the sky [blue]? ";
std::getline(std::cin, buffer);
if (buffer.size() == 0)
buffer="blue";
来源:https://stackoverflow.com/questions/39736176/providing-default-value-of-cin-input