C++ : initialize input programmatically

前端 未结 2 861
别跟我提以往
别跟我提以往 2020-12-10 18:01

If we have this code snippet:

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

And in the terminal, the input request woul

相关标签:
2条回答
  • 2020-12-10 18:26

    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.

    0 讨论(0)
  • 2020-12-10 18:36

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