两个输入C++来自 Bash 的 cin

Two inputs to C++ cin from Bash

本文关键字:来自 Bash cin C++ 输入 两个      更新时间:2023-10-16

我正在测试以下程序,其中涉及两个输入,第一个是 int 向量,第二个是 int。
主文件.cpp如下:

#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;
}

巴什脚本

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

编译我的代码并在文件夹中创建一个 A.exe。接下来,我尝试在 Bash 中打开它:

$ ./a.exe

然后我用向量 nums = {1,2,3} 对其进行测试,结果发现跳过了第二个 cin,如下所示。

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!

但是,如果我在没有 Bash 终端帮助的情况下直接打开 a.exe,这不是问题。那么是否可以进行一些更改,以便它在 Bash 下顺利运行呢?
提前感谢!
附言我使用Win7。

如果输入字面意思是

1 2 3 EOF

程序成功读取 1、2 和 3。它无法读取 EOF。之后,除非您采取措施清除cin的错误状态并添加代码以读取和丢弃EOF,否则它将不读取任何内容。

您可以使用cin.clear()cin.ignore()。您有cin.clear(),但这仍然EOF在流中。您需要添加一行以将其从输入流中丢弃。

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;

#include <limits>

能够使用std::numeric_limits.