Cam
Cam

Reputation: 15234

Redirect cin to a string

I want to have cin read input from a string.

Is there a way to 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

Upvotes: 10

Views: 5598

Answers (5)

bezxka
bezxka

Reputation: 1

also you can use this -

#include <string>

std::string str;

std::cin >> str;

if(str == "text")
{
    std::cout << "done";
}

Upvotes: 0

lifebalance
lifebalance

Reputation: 1927

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);

Upvotes: 1

pseudoramble
pseudoramble

Reputation: 2561

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!

Upvotes: 4

eq-
eq-

Reputation: 10096

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.

Upvotes: 6

Ben Voigt
Ben Voigt

Reputation: 283684

Try something like:

stringbuf s = string("123 ab");
cin.rdbuf(&s);

Upvotes: 1

Related Questions