pencilandpaper
pencilandpaper

Reputation: 43

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.

Upvotes: 1

Views: 24217

Answers (3)

Hemanth Kollipara
Hemanth Kollipara

Reputation: 1141

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

Upvotes: 1

finesse
finesse

Reputation: 117

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

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409176

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

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.

Upvotes: 2

Related Questions