[英]Two inputs to C++ cin from Bash
我正在測試以下程序,其中涉及兩個輸入,第一個是int的向量,第二個是int。
main.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;
}
Bash腳本
$ 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下平穩運行?
提前致謝!
PS我使用Win7的。
如果輸入字面是
1 2 3 EOF
您的程序成功讀取了1、2和3。 無法讀取EOF。 之后,除非您采取措施清除cin
的錯誤狀態並添加代碼以讀取和丟棄EOF
,否則它什么也不會讀取。
您可以cin.clear()
使用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
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.