提供cin输入的默认值 [英] Providing default value of cin input

查看:278
本文介绍了提供cin输入的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序使用 std :: cin 流读取用户输入。
在一个地方,我想提供默认输入,并让用户按原样接受(通过按Enter键)或在继续操作之前进行修改(通过使用退格键删除旧字符并添加新文本)。

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).

我知道可以将字符直接放入 cin.rdbuf 中,但这并不是我想要实现的。
我想在等待用户输入时将字符放在控制台光标所在的控制台窗口中,并且在用户接受它们之前不要阅读它们。用户还应该能够删除它们并编写自己的文本。

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.

可以使用 cin 来实现类似功能吗?还是我必须通过读取单个字符并重新绘制控制台内容来模拟这一点?

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?

推荐答案

不,这样的东西不可能用 std :: cin 完成。它的读取缓冲区直接从标准输入读取。标准输入是煮熟的字符流。所有编辑操作完全由操作系统的终端控制台处理,按 Enter 将导致应用程序的 std :: cin

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";

这篇关于提供cin输入的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆