C ++:以编程方式初始化输入 [英] C++ : initialize input programmatically

查看:56
本文介绍了C ++:以编程方式初始化输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果有以下代码段:

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

然后在终端中,输入请求将如下所示

And in the terminal, the input request would look like this

please enter a value: _

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

How can I programatically simulate a user's typing in it.

推荐答案

以下是使用

Here's a sample how to manipulate cin's input buffer using the rdbuf() function, to retrieve fake input from a 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在他的评论中所说的更接近) > IMHO),就是将您的阅读代码放入单独的函数中,例如

Another option (closer to what Joachim Pileborg said in his comment IMHO), is to put your reading code into a separate function e.g.

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

这使您可以进行不同的测试和生产呼叫,例如

This enables you to have different calls for testing and production, like

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

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

这篇关于C ++:以编程方式初始化输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆