将 std:cin 设置为字符串

Set std:cin to a string

为了便于测试,我希望将 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);

虽然我同意@πìντα ῥεῖ 正确 方法是将代码放入函数并向其传递参数,但 也可以使用 rdbuf() 来完成您的要求,像这样:

#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";
}