mario::konrad
programming / C++ / sailing / nerd stuff
C++ Stream Redirection
© 2010 / Mario Konrad

Small example of redirecting std::cin to read from a string instead from the console.

#include <iostream>
#include <sstream>

int main(int, char **)
{
    std::string s = "123";
    std::istringstream is(s);
    std::streambuf * cin_old = std::cin.rdbuf(is.rdbuf());

    int a;
    std::cin >> a;
    std::cout << "a=" << a << std::endl;
    return 0;
}

std::cin >> a on line 11 will now read from the provided string instead from the console.