首页 > 解决方案 > 将字符添加到 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 的情况下给它输入来测试程序,我该怎么做(从程序的源代码中)?

标签: c++std

解决方案


我不太确定你要做什么,但这是我的看法。
我对您的问题的理解可能是错误的,但是这个小片段会推动您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 运行


推荐阅读