我正在尝试编码 Q 并正在寻找一行代码来检测是否没有给出输入(用户只需按回车键)。相关的数据类型是 int。
我读过一些关于这个问题的其他问题,但不符合我的需要。我试过 eof 和其他类似的建议都无济于事......
这是代码 -
#include <iostream>
#include <math.h>
#include <vector>
using namespace std;
int main() {
int ogv,cgv=0,i,j=0,k;
int arr [3];
vector<int> ans;
while(true) {
cgv=0;
cin>>ogv;
//if("ogv is not a number, just an enter")
break;
arr[0]=floor(ogv/4);
arr[1]=floor(ogv/3);
arr[2]=floor(ogv/2);
for(i=0;i<=2;i++) {
if (arr[i]<0)
arr[i]=0;
cgv+=arr[i];
}
if(ogv>cgv) {
ans.push_back(ogv);
}
else {
ans.push_back(cgv);
}
j++;
}
for(k=0;k<j;k++) {
cout<<ans.at(k)<<endl;
}
}
非常感谢您的帮助...! :D
谢谢
最佳答案
您可以使用 noskipws manipulator
例子:
int x = -1;
cin>>noskipws>>x;
if(x==-1)
{
// no number was entered, the user just pressed enter
}
else
{
// the user entered a number
}
编辑:为了在循环中使用它,您需要在每次读取尝试之前丢弃当前缓冲区中的字符。
例如,如果用户输入数字 4 并在循环的第一次迭代中按下回车键,cin 将读取 4,但它会将行尾字符留在缓冲区中。当读取发生在第二次迭代时,cin 将在缓冲区中看到行尾字符,并将其视为用户按下 enter,退出循环。
我们可以使用 sync()
方法以丢弃缓冲区中的任何未读字符。我们需要在尝试从 cin
读取之前执行此操作:
cin.sync();
cin >> noskipws >> x;
关于c++ - 如何检测空的 int 输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10959699/