两个输入C++来自 Bash 的 cin
Two inputs to C++ cin from Bash
我正在测试以下程序,其中涉及两个输入,第一个是 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
.
相关文章:
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- 2D数组来自文本输入,中间有空格
- 通过继承类使用来自不同命名空间的运算符
- Cuda C++:设备上的Malloc类,并用来自主机的数据填充它
- 将bash参数传递给c++
- C++:来自外部文件的Trivia
- 如何处理来自核心指南检查器的关于gsl::at的静态分析警告
- 针对遗留库的链接:来自预制makefile的-lgfortranbegin
- 如何在C++中正确引用来自不同类的类的对象?
- Qt中来自不同功能的按钮引用
- C++包含来自 #include "DevEngine/Core.h" 的错误
- Eigen c++ 三角形来自
- 来自 DLL 的函数调用 [表观调用的括号前面的表达式必须具有(指向-)函数类型]
- 来自 Android 应用程序内部的 boost 类型的 boost::wrapexcept<boost::system::system_error> 的未捕获异常
- 中止信号来自 C++ 中的中止(3) (SIGABRT)
- 如何多次询问来自QML对话框的输入?
- 如何强制 Thrift 仅接受来自本地主机的连接
- 使 ld 忽略来自 /etc/ld.so.conf 的目录
- 在 Bash 脚本中处理来自子进程的信号
- 两个输入C++来自 Bash 的 cin