Redirect cin to a string

前端 未结 4 673
长发绾君心
长发绾君心 2020-12-16 19:14

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.readFro         


        
相关标签:
4条回答
  • 2020-12-16 19:39

    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!

    0 讨论(0)
  • 2020-12-16 19:54

    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.

    0 讨论(0)
  • 2020-12-16 19:56

    Try something like:

    stringbuf s = string("123 ab");
    cin.rdbuf(&s);
    
    0 讨论(0)
  • 2020-12-16 20:00

    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);
    
    0 讨论(0)
提交回复
热议问题