简体   繁体   English

在 C++ 中检查输入类型

[英]to check type of input in c++

## To check type of data entered in cpp ## ##检查cpp中输入的数据类型##

int main()
{
    int num;
    stack<int> numberStack;
    while(1)
    {
        cin>>num;
        if(isdigit(num))
            numberStack.push(num);
        else
            break;
    }
return(0);
}

If I declare a variable as interger, and I input an alphabet, say 'B', instead of the number, can I check this behavior of user?如果我将一个变量声明为整数,并输入一个字母表,比如“B”,而不是数字,我可以检查用户的这种行为吗? My code above exits when first number is entered and does not wait for more inputs.当输入第一个数字并且不等待更多输入时,我上面的代码退出。

First of all, the std::isdigit function checks if a character is a digit.首先, std::isdigit函数检查字符是否为数字。

Secondly, by using the input operator >> you will make sure that the input is a number, or a state flag will be set in the std::cin object.其次,通过使用输入操作符>>您将确保输入是一个数字,或者在std::cin对象中设置一个状态标志 Therefore do eg因此做例如

while (std::cin >> num)
    numberStack.push(num);

The loop will then end if there's an error, end of file, or you input something that is not a valid int .如果出现错误、文件结束或您输入的内容不是有效的int ,则循环将结束。

First take your input as string首先将您的输入作为字符串

Using builtin libraries like isdigit() classify it as an integer使用像 isdigit() 这样的内置库将其分类为整数

else if it contains '.'then its a float否则,如果它包含 '.' 那么它是一个浮点数

else if it a alphanumerical the it is a string thats it否则,如果它是字母数字,那么它就是一个字符串

Code for this is below,代码如下,

#include<iostream>
#include<string.h>
using namespace std;

int isint(char a[])
{
    int len=strlen(a);
    int minus=0;
    int dsum=0;
    for(int i=0;i<len;i++)
    {
        if(isdigit(a[i])!=0)
            dsum++;
        else if(a[i]=='-')
            minus++;        
    }
    if(dsum+minus==len)
        return 1;
    else 
        return 0;
}
int isfloat(char a[])
{
    int len=strlen(a);
    int dsum=0;
    int dot=0;
    int minus=0;
    for(int i=0;i<len;i++)
    {
        if(isdigit(a[i])!=0)
        {
            dsum++;
        }
        else if(a[i]=='.')
        {
            dot++;
        }
        else if(a[i]=='-')
        {
            minus++;
        }       
    }
    if(dsum+dot+minus==len)
        return 1;
    else
        return 0;
}
int main()
{
    char a[100];
    cin>>a; 
    
    if(isint(a)==1)
    {
        cout<<"This input is of type Integer";
    }
    else if(isfloat(a)==1)
    {
        cout<<"This input is of type Float";
    }
    else
    {
        cout<<"This input is of type String";
    }
    
}

use cin.fail() to check error and clean the input buffer.使用 cin.fail() 检查错误并清理输入缓冲区。

int num;
while (1) {
    cin >> num;
    if (cin.fail()) {
        cin.clear();
        cin.sync();
        cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        continue;
    }
    if (num == -1) {
        break;
    }
    numberStack.push(num);
}   

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM