Alex Bollbach
Alex Bollbach

Reputation: 4600

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

Upvotes: 1

Views: 3396

Answers (2)

Jerry Coffin
Jerry Coffin

Reputation: 490768

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

Upvotes: 3

πάντα ῥεῖ
πάντα ῥεῖ

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

Upvotes: 4

Related Questions