c++ - 将字符添加到 std::cin
问题描述
我正在做一个计算器。
我从 GUI 检索用户输入并将其存储在std::vector<char> c
现在我需要把每个字符都c
添加进去std::cin
,这是因为计算器引擎是基于的std::cin
,我只想在上面添加一个 GUI 层。
我写了一些示例代码来演示我的问题,这不是实际的应用程序:
#include <iostream>
#include <vector>
int main()
{
int length = 6;
std::vector<char> in(length);
in[0] = 'H';
in[1] = 'e';
in[2] = 'l';
in[3] = 'l';
in[4] = 'o';
in[5] = '\0';
for (int i = 0; i < length; ++i)
{
char a = in[i];
std::cout << "a: " << a << std::endl;
std::cin.putback(a);
}
char y = 0;
while(std::cin >> y)
{
std::cout << "y: " << y << std::endl;
if (y == '\0')
{
std::cout << "This is the end!" << std::endl;
}
}
}
我的预期结果是从while(std::cin >> y)
循环中获得输出。
问题是没有输出。
编辑:另一种思考我的问题的方式是。假设我制作了一个依赖于用户输入的程序,std::cin
输入可以是任何主要类型。现在,如果我想通过在没有 shellscripting 的情况下给它输入来测试程序,我该怎么做(从程序的源代码中)?
解决方案
我不太确定你要做什么,但这是我的看法。
我对您的问题的理解可能是错误的,但是这个小片段会推动您std::vector<char>
进入std::cin
然后遍历它,直到您遇到 EOF。
#include <iostream>
#include <vector>
int main() {
int length = 6;
std::vector<char> in(length);
in[0] = 'H';
in[1] = 'e';
in[2] = 'l';
in[3] = 'l';
in[4] = 'o';
in[5] = '\0';
for (auto a = in.crbegin(); a != in.crend(); ++a) {
std::cout << "a: " << *a << std::endl;
std::cin.putback(*a);
}
while (std::cin) {
char y;
std::cin >> y;
std::cout << "y: " << y << std::endl;
if (y == '\0') {
std::cout << "This is the end!" << std::endl;
break;
}
}
}
我猜它对你不起作用,因为第一个元素std::cin
是 EOF,因为std::cin.pushback()
它作为 LIFO 运行
推荐阅读
- https - 在双 nat 后面的 tls 中包装 http 服务器
- javascript - forEach() 不能与我的 HTML 标签一起正常工作,在 JSON 上循环
- vaadin14 - 如何更改 Vaadin-Select 悬停颜色
- python - 如何从 .env 文件成功加载 API 密钥
- python - ImportError:无法从“tensorflow.python.keras.utils.conv_utils”导入名称“deconv_length”
- javascript - Threejs不会在chrome android上加载gltf模型
- ansible - 具有独特参数的 Cisco 路由器配置的 Ansible Playbook
- automated-tests - 空手道测试 - 以无头模式从电子邮件访问 PDF 链接的问题(从 Jenkins 运行)
- yaml - Swagger 编辑器中的 YAML 枚举解析器问题
- python - 如何在 mongo DB 上插入数据