将std:cin设置为字符串 [英] Set std:cin to a string
本文介绍了将std:cin设置为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为了便于测试,我希望将Cin的输入设置为可以硬编码的字符串。
For ease of testing I wish to set Cin's input to a string I can hardcode.
例如,
std::cin("test1 \ntest2 \n");
std::string str1;
std::string str2;
getline(cin,str1);
getline(cin,str2);
std::cout << str1 << " -> " << str2 << endl;
将读出:
test1 -> test2
推荐答案
最好的IMO解决方案是重构您的核心代码接受 std :: istream
引用的函数:
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);
并用于生产:
work_with_input(cin);
这篇关于将std:cin设置为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文