Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect cin to a string

Tags:

c++

iostream

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
like image 338
Cam Avatar asked Feb 07 '11 18:02

Cam


People also ask

Can we use CIN for string?

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.

Does CIN take newline?

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.

How do you write to stdout to a file in C++?

I/O Redirection in C++ For Example, to redirect the stdout to say a textfile, we could write : freopen ("text_file. txt", "w", stdout);

How do you close a CIN?

On Windows you'd use Ctrl-Z, on UNIXes you'd use Ctrl-D.


1 Answers

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.

like image 165
eq- Avatar answered Nov 07 '22 07:11

eq-