user5797668 user5797668 - 4 months ago 9
C++ Question

Set std:cin to a string

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

Answer

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);