C++ C+的两个输入+;来自Bash的cin
我正在测试以下程序,其中涉及两个输入,第一个是int向量,第二个是int。C++ C+的两个输入+;来自Bash的cin,c++,bash,C++,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
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;
}
编译我的代码并在文件夹中创建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;
cout>i){
nums.推回(i);
}
谢谢你的建议!现在,当前程序运行良好。似乎我们必须让程序读取一些“无效”的东西,比如“eof”,或者其他什么,来终止进程。但是,在代码中将所有int替换为string之后,无论我如何尝试“\n”或“\r”,它都无法工作。我认为它们都被认为是弦。在这种情况下,Bash中是否有任何有效的EOF选项,相当于cmd中的“^z”?我对Bash非常陌生。如果您想读取字符串,您必须使用不同的方法,因为任何非空白字符都可以读入字符串。您可以使用std::getline
读取一行文本,然后使用std::istringstream
将该行的内容读取到向量。
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>