0

我正在尝试使用 isaplha() 函数来检查每个字符串的每个字符以确保它是否是字母。但由于某种原因,它不起作用。尽管有 if 语句的参数,程序总是进入 printf() 函数。代码似乎一切正常:

#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;
}
4

1 回答 1

0

给你。

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

程序输出可能看起来像

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

考虑到函数 gets 不是标准的 C 函数,C 标准不再支持它。

而这张支票

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

必须放在内部循环之外,该内部循环必须只检查字符串的字符而不是整个字符数组。

于 2019-08-01T14:39:31.667 回答