write to istream

Hi all,

Is there a way to set istream buffer content? I need to write string into std::cin in other way than user's input. I've tried with putback() but it only works with one char.
You cannot write to an input stream.

Putback or unget is a conveniece for parsers that need to peek into the stream to see the next character to decide whether to continue or not. The data only goes back into a buffer, not all the way back to the source.
Last edited on
Why do you want to write a string to std::cin?
Last edited on
I have almost complete program for parsing expressions, where expression is parsed from std::cin in 5 different classes. I need to add option for parsing expression which doesn't come from user's input, but from some defined source (file for example). It will be much easier for me to just write value into cin than rewriting whole parsing.
You need to write your parser to read from a std::istream&. Then you just pass in different types of std::istream

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream> // for std::cin
#include <sstream> // for string input
#include <fstream> // for file input

void parse_input(std::istream& is);

int main()
{
    std::ifstream ifs("my-input.txt"); // file input

    parse_input(ifs); // parse a std::ifstream

    std::istringstream iss("4 + 7 * 6 / 9"); // string input

    parse_input(iss); // parse a string stream

    parse_input(std::cin); // parse from standard input stream
}
Last edited on
Thx Galik, Im already writing something similar, but it still requires rewriting part of the project. I hoped for solution which requires one or two lines of code.
Well hopefully you just need to replace your std::cin with a reference to a std::istream throughout. It might be a bit of work, but its the 'right thing to do' ;o)
Topic archived. No new replies allowed.