0

Possible Duplicate:
Redirect cin to a string

I saw this post on how to redirect cout to a string. But how to redirect the cin to a string, just like redirecting cin to a file using freopen, so that when I do cin>>a_int;, I will get an int from the string? Can I do similarly with setbuf (stdin , buffer);

Community
  • 1
  • 1

1 Answers1

0

I'm answering this with your end goal in mind...

when I do cin>>a_int;, I will get an int from the string?

You can do that without redirecting cin by using std::istringstream

Usage would look like this.

#include <sstream>

std::istringstream is(your_string);
is >> a_int;
Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
  • I know this. But I need to `cin>>a_int` to get the number.please remove your answer so that i can delete this post. it is a duplicate. –  Feb 01 '12 at 20:13
  • 1
    That other question already has the answer, but perhaps you should consider why you have to redirect `cin` instead of using a `stringstream` directly. Remember, `cin` and `cout` are global variables and you should treat them just like any global variables; avoid them as much as possible. You can write better code by passing the streams you need as parameters, and if you need to access the standard input and output then you can pass `cin` and `cout` as parameters. – bames53 Feb 01 '12 at 20:44