C++ : initialize input programmatically

标签 c++ linux terminal

如果我们有这段代码:

int a;
cout << "please enter a value: "; 
cin >> a;

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

please enter a value: _

我如何以编程方式模拟用户在其中的输入。

最佳答案

下面是一个示例,说明如何使用 rdbuf() 操作 cin 的输入缓冲区 函数,从 std::istringstream

检索假输入
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main() {

    istringstream iss("1 a 1 b 4 a 4 b 9");
    cin.rdbuf(iss.rdbuf());  // This line actually sets cin's input buffer
                             // to the same one as used in iss (namely the
                             // string data that was used to initialize it)
    int num = 0;
    char c;
    while(cin >> num >> c || !cin.eof()) {
        if(cin.fail()) {
            cin.clear();
            string dummy;
            cin >> dummy;
            continue;
        }
        cout << num << ", " << c << endl;
    }
    return 0;
}

See it working


另一种选择(更接近 Joachim Pileborg 在 his comment 恕我直言中所说的)是将您的阅读代码放入单独的函数中,例如

int readIntFromStream(std::istream& input) {
    int result = 0;
    input >> result;
    return result;
}

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

// Testing code
std::istringstream iss("42");
int value = readIntFromStream(iss);

// Production code
int value = readIntFromStream(std::cin);

关于C++ : initialize input programmatically,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27656187/

相关文章:

c++ - 无法从 C++ 中的函数捕获异常

c++ - DllMain Attach 和 Detach 过程中的使用限制

python - 更新到 Python 3.8 - 终端无法打开 - [已修复] 但细节不明白

linux - 重新加载 Linux 桌面而不重新启动或注销并重新登录?

java - C++ 中 BufferedImage 的替代

c++ - 如何动态分配 CFile 类型的变量? (C++、CFile、新)

c++ - 保持相同数量的子进程

linux - mac上的常用命令行

linux - NPM 安装 PM2 -g (Ubuntu 14.04 x64) 时出错

linux - 我如何使用 perl cd 进入一个目录?