如何检测空int输入?

时间:2012-06-09 09:00:29

标签: c++ input

我正在尝试编码Q并且正在寻找一行代码来检测是否没有给出输入(用户只需按Enter键)。有关的数据类型是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

由于

2 个答案:

答案 0 :(得分:2)

您可以使用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并在循环的第一次迭代中按Enter键,则cin将读取4,但它会将行尾字符留在缓冲区中。当在第二次迭代中发生读取时,cin将在缓冲区中看到行尾字符,并将其视为用户按下回车键,退出循环。

我们可以使用sync()方法来丢弃缓冲区中的任何未读字符。我们需要在尝试阅读cin之前执行此操作:

cin.sync();
cin >> noskipws >> x;

答案 1 :(得分:0)

如果您使用流输入整数,它会在读取之前跳过空格。这包括您可以输入的任意数量的换行符。

换句话说:

int i;
std::cin >> i;

在找到一些非空格之前不会返回。

如果你想检测一个空行,我通常只使用getline来获取一个字符串的完整行,然后使用字符串流将其转换为整数,如:

#include <iostream>
#include <string>
#include <sstream>

int main (void) {
    std::string s;
    int i = -1;

    std::cout << "Enter string: ";
    std::getline (std::cin, s);
    std::cout << "String is '" << s << "'\n";

    std::stringstream ss (s);
    ss >> i;
    std::cout << "Integer is " << i << "\n";

    return 0;
}

成绩单如下:

pax> ./qq
Enter string: 
String is ''
Integer is -1

pax> ./qq
Enter string: hello
String is 'hello'
Integer is -1

pax> ./qq
Enter string: 0
String is '0'
Integer is 0

pax> ./qq
Enter string: 1
String is '1'
Integer is 1

pax> ./qq
Enter string: 314159
String is '314159'
Integer is 314159