简体   繁体   中英

to check type of input in c++

## To check type of data entered in 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? 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.

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. 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 .

First take your input as string

Using builtin libraries like isdigit() classify it as an integer

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.

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);
}   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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