I want to have cin read input from a string.
Is there a way to have it do this?
Something like this:
const char * s = \"123 ab\";
cin.readFro
I would recommend using a string stream. You can use the overloaded I/O operators like you would with standard in/standard out. Something like this:
string tempString = "123 ab";
int firstArg;
string secondArg;
stringstream stream(tempString);
stream >> firstArg >> secondArg;
cout << firstArg << " " << secondArg;
I would personally find this to be a little more clear than reading in a string to standard in and then using standard in's I/O operators, but maybe there's a reason you want to read it to standard in first that I don't realize.
Hope this helps!
Like this:
#include <sstream>
#include <iostream>
std::istringstream stream("Some string 123");
streambuf* cin_backup = std::cin.rdbuf(stream.rdbuf());
You might want to back up the original rdbuf of std::cin, if you want to use it again.
Try something like:
stringbuf s = string("123 ab");
cin.rdbuf(&s);
In C++17, Ben Voigt's solution won't compile unless you use basic_stringbuf
. Instead use the one below:
stringbuf s;
const char *userInput = "10 1 2 3 4 5 6 7 8 9 10 3 7";
s.sputn(userInput, strlen(userInput));
cin.rdbuf(&s);