Providing default value of cin input

拟墨画扇 提交于 2020-01-30 06:47:05

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!