0

I am trying to use isaplha() function in order to check every character of each string to be sure if it is alphabetic. But for some reason it does not work. Program always goes into printf() function despite of an argument of an if statement. It seems that everything is okay with the code:

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define N 5

int main(void) 
{
    char string[N][50];
    int i,j;

    printf("Enter an array of N strings:\n");

    for(i=0;i<N;i++){
        gets(string[i]);
    }

    for(i=0;i<N;i++){
        for(j=0;j<50;j++){
            if(isalpha(string[i][j])){
                printf("\nIt should not work with numbers");
            }
        }
    }

    return 0;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335

1 Answers1

0

Here you are.

#include <stdio.h>
#include <string.h>
#include <ctype.h>

#define N   5
#define M   50

int main(void) 
{
    char string[N][M];

    printf( "Enter an array of %d strings:\n", N );

    for ( int i = 0; i < N; i++ )
    {
        fgets( string[i], sizeof( string[i] ), stdin );
        string[i][strcspn( string[i], "\n" )] = '\0';
    }

    for ( int i = 0; i < N; i++ )
    {
        const char *p = string[i];

        while ( *p != '\0' && !isalpha( ( unsigned char ) *p ) ) ++p;

        if ( *p != '\0') printf( "\n\"%s\" should not work with numbers", string[i] );
    }

    return 0;
}

The program output might look like

Enter an array of 5 strings:

12345
123A5
87654
8765B
Hello

"123A5" should not work with numbers
"8765B" should not work with numbers
"Hello" should not work with numbers

Take into account that the function gets is not a standard C function that is it is not supported any more by the C Standard.

And this check

        if(isalpha(string[i][j])){
            printf("\nIt should not work with numbers");
        }

must be placed outside the inner loop that must check only the characters of a string not of the whole character array.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335