Search code examples
c++cinstreambuf

preload cin with a string of commands


I'm testing functions that require several console commands before they can execute. Instead of having to type those commands every single time I want to test the functionality of a particular method, I want to be able to just paste a line or two of code in my source that effectively does the same thing as typing the commands would do. I tried the following code but it seems like it just loops infinitely.

streambuf *backup;
backup = cin.rdbuf();
stringbuf s = stringbuf("1 a 1 b 4 a 4 b 9");
cin.rdbuf(&s);
cin.rdbuf(backup); 

Solution

  • The following code works well for me

    #include <iostream>
    #include <sstream>
    #include <string>
    using namespace std;
    
    int main() {
    
        istringstream iss("1 a 1 b 4 a 4 b 9");
        cin.rdbuf(iss.rdbuf());
        int num = 0;
        char c;
        while(cin >> num >> c || !cin.eof()) {
            if(cin.fail()) {
                cin.clear();
                string dummy;
                cin >> dummy;
                continue;
            }
            cout << num << ", " << c << endl;
        }
        return 0;
    }