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

Ikb*_*bel 5 c++ linux terminal

如果我们有这段代码:

int a;
cout << "please enter a value: "; 
cin >> a;
Run Code Online (Sandbox Code Playgroud)

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

please enter a value: _
Run Code Online (Sandbox Code Playgroud)

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

πάν*_*ῥεῖ 9

下面是一个如何cin使用该rdbuf()函数操作输入缓冲区以从中检索伪输入的示例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;
}
Run Code Online (Sandbox Code Playgroud)

看它工作


另一个选择(更接近Joachim Pileborg在他的评论 IMHO中所说的),是将你的阅读代码放入一个单独的函数,例如

int readIntFromStream(std::istream& input) {
    int result = 0;
    input >> result;
    return result;
}
Run Code Online (Sandbox Code Playgroud)

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

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

// Production code
int value = readIntFromStream(std::cin);
Run Code Online (Sandbox Code Playgroud)