C++:以编程方式初始化输入 [英] C++ : initialize input programmatically
本文介绍了C++:以编程方式初始化输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我们有这个代码片段:
If we have this code snippet:
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.
推荐答案
这里是如何使用 rdbuf()
函数,从 检索假输入std::istringstream
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;
}
另一种选择(更接近 Joachim Pileborg 在他的评论 恕我直言),就是把你的阅读代码放到一个单独的函数中,例如
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屋!
查看全文