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.readFrom(s);//<---- I want something like this
int i;
cin>>i;
cout<<i; //123
Inputting a string You can use cin but the cin object will skip any leading white space (spaces, tabs, line breaks), then start reading when it comes to the first non-whitespace character and then stop reading when it comes to the next white space. In other words, it only reads in one word at a time.
In the line “cin >> c” we input the letter 'Z' into variable c. However, the newline when we hit the carriage return is left in the input stream. If we use another cin, this newline is considered whitespace and is ignored.
I/O Redirection in C++ For Example, to redirect the stdout to say a textfile, we could write : freopen ("text_file. txt", "w", stdout);
On Windows you'd use Ctrl-Z, on UNIXes you'd use Ctrl-D.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With