【问题标题】:Add characters into std::cin [duplicate]将字符添加到 std::cin [重复]
【发布时间】:2019-01-21 15:30:10
【问题描述】:

我正在做一个计算器。

我从 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 &gt;&gt; y) 循环中获得输出。
问题是没有输出。

编辑: 思考我的问题的另一种方式是。假设我制作了一个依赖于来自std::cin 的用户输入的程序,并且输入可以是任何主要类型。现在,如果我想通过在没有 shellscripting 的情况下给它输入来测试程序,我该怎么做(从程序的源代码中)?

【问题讨论】:

  • 评论不用于扩展讨论;这个对话是moved to chat
  • 你希望这段代码做什么,它实际上做了什么?
  • 请注意,putback 通常对您可以放回的字符数有限制,该限制通常为 1。
  • @PeteBecker 即使它是 1,它也会打印一些东西。根本没有输出

标签: c++ std


【解决方案1】:

我不太确定你想要什么,但这是我的看法。
我对你的问题的理解可能是错误的,但是这个小 sn-p 将你的 std::vector&lt;char&gt; 推入 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 运行

【讨论】:

  • 问题是while (std::cin)没有输出
  • 请阅读我的回答。您从 '\0' 开始,除非您打算立即退出 while 循环,否则您需要考虑字符的顺序
  • 即使您将'\0' 替换为另一个任意的char(比如'!'),问题仍然存在。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-22
  • 2015-12-10
  • 2018-10-26
  • 2022-09-27
  • 2016-02-03
  • 1970-01-01
  • 2018-07-27
相关资源
最近更新 更多