如果我们有这段代码:
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;
}
另一种选择(更接近 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/