jeudi 26 octobre 2017

Alphanumeric in c

I have written 2 similar kind of codes to check if a string is alphanumeric . I think both the codes represent same logic. But why they are giving different output? What is the loophole there? I just check with the input 'abc123' . One of the code is giving 'the string is alphanumeric' but another one is giving 'string is not alphanumeric'.

#include<stdio.h>

int main() {

char s[20];
printf("enter a string : ");
gets(s);
int i=0,k,A=0,D=0;
for(i=0;s[i];i++)
{


    if(isalpha(s[i]))
    {

        A=1;
    }
    if (isdigit(s[i]))
    {

        D=1;
    }
}
printf("A=%d D=%d",A,D);
if(A==1 && D==1)
    printf("\nstring is alphanumeric");
else
    printf("\nstring is not alphanumeric");

} This is giving the output as alphanumeric for the above input.

int main() {

char s[20];
printf("enter a string : ");
gets(s);
int i=0,k,A=0,D=0;
for(i=0;s[i];i++)
{


    if(isalpha(s[i]))
    {

        A=1;
    }
    if (isdigit(s[i]))
    {

        D=1;
    }
}
printf("A=%d D=%d",A,D);
if(A==1 && D==1)
    printf("\nstring is alphanumeric");
else
    printf("\nstring is not alphanumeric");

}

But this code is showing that the string is not alphanumeric.

Aucun commentaire:

Enregistrer un commentaire