Set std:cin to a string

↘锁芯ラ 提交于 2020-04-30 05:43:34

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!