C:以编程方式初始化输入

前端之家收集整理的这篇文章主要介绍了C:以编程方式初始化输入前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

如果我们有这段代码

  1. int a;
  2. cout << "please enter a value: ";
  3. cin >> a;

在终端中,输入请求看起来像这样

  1. please enter a value: _

我如何以编程方式模拟用户在其中键入内容.

最佳答案
以下是使用rdbuf()函数操作cin输入缓冲区的示例,以从std :: istringstream检索伪输入

  1. #include

See it working

另一个选择(更接近Joachim Pileborg在his comment恕我直言中所说的)是将你的阅读代码放入一个单独的功能,例如:

  1. int readIntFromStream(std::istream& input) {
  2. int result = 0;
  3. input >> result;
  4. return result;
  5. }

这使您可以对测试和生产进行不同的调用,例如

  1. // Testing code
  2. std::istringstream iss("42");
  3. int value = readIntFromStream(iss);
  4. // Production code
  5. int value = readIntFromStream(std::cin);

猜你在找的Linux相关文章