Redirect cin to a string

让人想犯罪 __ 提交于 2019-11-27 18:14:33

问题


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

回答1:


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.




回答2:


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!




回答3:


Try something like:

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



回答4:


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


来源:https://stackoverflow.com/questions/4925150/redirect-cin-to-a-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!