将std:cin设置为字符串

Set std:cin to a string

本文关键字:字符串 设置 cin std      更新时间:2023-10-16

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

在我看来,最好的解决方案是将核心代码重构为一个接受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";
}