简体   繁体   中英

Two inputs to C++ cin from Bash

I am testing the following program, where two inputs are involved, the first being a vector of int, and second being an int.
The main.cpp file is the following:

#include<iostream>
#include<vector>
#include<algorithm>

using namespace std;

void print(vector<int> & vec) {
    for (vector<int>::iterator it = vec.begin(); it != vec.end(); ++it) 
        cout << *it << " ";
    cout << endl;
}

int main() {
    vector<int> nums{}; 
    int i;
    int target;

    cout << "Please enter a vector of integers:\n";
    while (cin >> i) {
        nums.push_back(i);
    }
    cout << "Vector of Integers:" << endl;
    print(nums);
    cin.clear();
    cout << "Please enter an integer:" << endl;
    cin >> target;
    cout << "Checking whether " << target << " is in the vector...\n";
    if (find(nums.begin(), nums.end(), target) != nums.end()) {
        cout << "Target found!\n"; 
    }
    else {
        cout << "Target not found!\n"; 
    }
    return 0;
}

Bash script

$ g++ -std=c++11 main.cpp

compiles my code and creates an a.exe in the folder. Next, I try to open it in Bash:

$ ./a.exe

Then I test it with the vector nums = {1,2,3}, and it turns out that the second cin is skipped, as you can see below.

Please enter a vector of integers:
1 2 3 EOF
Vector of Integers:
1 2 3
Please enter an integer:
Checking whether 0 is in the vector...
Target not found!

However, it is not a problem if I open the a.exe directly, without the help of the Bash terminal. So is it possible to make some changes so that it will run smoothly under Bash?
Thanks in advance!
PS I use Win7.

If the input literally is

1 2 3 EOF

your program reads 1, 2, and 3 successfully. It fails to read EOF. After that, it reads nothing unless you take steps to clear the error state of cin and add code to read and discard the EOF .

You can use cin.clear() and cin.ignore() for that. You have cin.clear() but that still leaves EOF in the stream. You need to add a line to discard that from the input stream.

cout << "Please enter a vector of integers:\n";
while (cin >> i) {
    nums.push_back(i);
}
cout << "Vector of Integers:" << endl;
print(nums);
cin.clear();

// Need this.
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

cout << "Please enter an integer:" << endl;
cin >> target;

Add

#include <limits>

to be able to use std::numeric_limits .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM