问题
For ease of testing I wish to set Cin's input to a string I can hardcode.
For example,
std::cin("test1 \ntest2 \n");
std::string str1;
std::string str2;
getline(cin,str1);
getline(cin,str2);
std::cout << str1 << " -> " << str2 << endl;
Will read out:
test1 -> test2
回答1:
The best solution IMO is to refactor your core code to a function that accepts a std::istream
reference:
void work_with_input(std::istream& is) {
std::string str1;
std::string str2;
getline(is,str1);
getline(is,str2);
std::cout << str1 << " -> " << str2 << endl;
}
And call for testing like:
std::istringstream iss("test1 \ntest2 \n");
work_with_input(iss);
and for production like:
work_with_input(cin);
回答2:
While I agree with @πάντα ῥεῖ that the right way to do this is by putting the code into a function and passing a parameter to it, it is also possible to do what you're asking for, using rdbuf()
, something like this:
#include <iostream>
#include <sstream>
int main() {
std::istringstream in("test1 \ntest2 \n");
// the "trick": tell `cin` to use `in`'s buffer:
std::cin.rdbuf(in.rdbuf());
// Now read from there:
std::string str1;
std::string str2;
std::getline(std::cin, str1);
std::getline(std::cin, str2);
std::cout << str1 << " -> " << str2 << "\n";
}
来源:https://stackoverflow.com/questions/38836016/set-stdcin-to-a-string