c++ - 设置标准 :cin to a string

标签 c++ stream cin

为了便于测试,我希望将 Cin 的输入设置为一个我可以硬编码的字符串。

例如,

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 引用的函数:

void work_with_input(std::istream& is) {
    std::string str1;
    std::string str2;
    getline(is,str1);
    getline(is,str2);

    std::cout << str1 << " -> " << str2 << endl;
}

并要求像这样进行测试:

std::istringstream iss("test1 \ntest2 \n");

work_with_input(iss);

对于像这样的生产:

work_with_input(cin);

关于c++ - 设置标准 :cin to a string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38836016/

相关文章:

powershell - 如何从PowerShell读取PowerShell的调试流?

c# - using() 并处理多个包装流

c# - 产生多个 IEnumerables

c++ - 有条件地打破一长串输入?

c++ - 生成可以区分 ID(Foo::a()) 和 ID(Foo::b()) 的唯一标识符

c++ - std::ifstream 类的设计

c++ - 如何定义迭代器类成员的类型以使用 STL 容器方法?

c++ - 在子类中定义可变函数特化

c++ - C++中std::cin对象的规则是什么?

c++ - Cin 被跳过,cin.ignore 不工作