Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 644
Ikbel Avatar asked Dec 26 '14 10:12

Ikbel


2 Answers

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);
like image 173
πάντα ῥεῖ Avatar answered Sep 29 '22 07:09

πάντα ῥεῖ


Hey why don't you write your input in a plain text file and redirect it to cin ??? It's the simplest method.

Open Command Prompt. Suppose your text file which will used as input is in.txt and your program is prog.exe. Keep the text file and the program in same folder. cd to your folder. Then type:

prog.exe < in.txt

Remember, your text file will be treated exactly as it is. Shoudld't be a problem if you know cin only catches upto next whitespace character, while string input functions (e.g. cin.getline) only catch upto next newline character.

//Sample prog.cpp
#include <iostream>

using namespace std;

int main()
{
    int num;
    do
    {
        cin >> num;
        cout << (num + 1) << endl;
    }
    while (num != 0);

    return 0;
}

//Sample in.txt
2
51
77
0

//Sample output
3
52
78
1

Sorry if you are on other platform, I don't know about them.

like image 39
AneesAhmed777 Avatar answered Sep 29 '22 07:09

AneesAhmed777