C++ : initialize input programmatically

前端 未结 2 877
别跟我提以往
别跟我提以往 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 
    
    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.

提交回复
热议问题