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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#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.