10

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
Cam
  • 14,930
  • 16
  • 77
  • 128
  • If you want to use a char array instead of a std:string you could use cin.getline (s,n); Where n is the "number of characters to store (including the terminating null character)". See http://www.cplusplus.com/reference/iostream/istream/getline/. There's also a getline for std::string, see http://www.cplusplus.com/reference/string/getline/ – anno Feb 07 '11 at 20:14
  • @anno: Read `cin` **from** a string, not from `cin` into a string. – Ben Voigt Feb 08 '11 at 02:48

4 Answers4

6

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.

eq-
  • 9,986
  • 36
  • 38
4

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!

pseudoramble
  • 2,541
  • 22
  • 28
1

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);
lifebalance
  • 1,846
  • 3
  • 25
  • 57
1

Try something like:

stringbuf s = string("123 ab");
cin.rdbuf(&s);
Ben Voigt
  • 277,958
  • 43
  • 419
  • 720