Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
589 views
in Technique[技术] by (71.8m points)

linux - C++ : initialize input programmatically

If we have this code snippet:

int a;
cout << "please enter a value: "; 
cin >> a;

And in the terminal, the input request would look like this

please enter a value: _

How can I programatically simulate a user's typing in it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here's a sample how to manipulate cin's input buffer using the rdbuf() function, to retrieve fake input from a std::istringstream

#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main() {

    istringstream iss("1 a 1 b 4 a 4 b 9");
    cin.rdbuf(iss.rdbuf());  // This line actually sets cin's input buffer
                             // to the same one as used in iss (namely the
                             // string data that was used to initialize it)
    int num = 0;
    char c;
    while(cin >> num >> c || !cin.eof()) {
        if(cin.fail()) {
            cin.clear();
            string dummy;
            cin >> dummy;
            continue;
        }
        cout << num << ", " << c << endl;
    }
    return 0;
}

See it working


Another option (closer to what Joachim Pileborg said in his comment IMHO), is to put your reading code into a separate function e.g.

int readIntFromStream(std::istream& input) {
    int result = 0;
    input >> result;
    return result;
}

This enables you to have different calls for testing and production, like

// Testing code
std::istringstream iss("42");
int value = readIntFromStream(iss);

// Production code
int value = readIntFromStream(std::cin);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...