0

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); 
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
user2514676
  • 473
  • 2
  • 6
  • 18
  • Do you want/need `cin` to keep reading from stdin after it's done with the predefined string, or should it treat the string as all the input it's going to get? – jwodder Jul 17 '14 at 18:41
  • 2
    Why not using the shell's input redirection features to feed `cin` from a file? – πάντα ῥεῖ Jul 17 '14 at 18:42
  • @jwodder I want to still be able to use cin normally afterwards – user2514676 Jul 17 '14 at 18:55
  • @πάντα ῥεῖ because that's more steps (more tedious) than using a few lines of code. (I would have open, edit, & save the file instead of edit a string) – user2514676 Jul 17 '14 at 18:57
  • 1
    Consider having your functions accept an arbitrary stream as an argument (`std::istream&`) instead of forcing to cin. – zneak Jul 17 '14 at 19:07

1 Answers1

2

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;
}
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190