c - 有没有办法检查数组中字符串的大写和 isalpha 大小写?

标签 c

while(1)
    {

        char buff[1000];
        printf("Enter the word: ");
        fgets(buff, 1000, stdin);
        if(!strcmp(buff, "\n"))//empty search then break the loop
        {
            fprintf(stderr, "Exiting the program\n");
            break;
        }


        int error = 0;
        int i = 0;
        while(buff[i] != '\0')
        {

            if(buff[i] >= 33 && buff[i] <= 96)
            {
                break;
            }

            error = 1;
            i++;
        }

        if(error == 0)
        {
            fprintf(stderr, "Please enter something containing only lower-case letters\n");
        }

        }



我希望 hello World 的输出是 Please enter something containing only lower-case letters,但我没有收到该错误。 如果我输入 World hello,我会得到预期的结果,它会打印错误消息。

有没有办法对整个阵列使用 isalpha?

最佳答案

您不应硬编码字母值,而应使用实际值。在此问题中,'a''z' 范围之外的任何字母都是无效的。但是使用库函数 isalpha()islower() 更便于移植,因为不能保证字母值是连续的。

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

int main(void)
{
    while(1) {

        char buff[1000];
        printf("Enter the word: ");
        fgets(buff, sizeof buff, stdin);
        if(!strcmp(buff, "\n")) {
            fprintf(stderr, "Exiting the program\n");
            break;
        }
        int error = 0;
        int i = 0;
        while(buff[i] != '\0') {
            if(isalpha(buff[i]) && !islower(buff[i])) {
                error = 1;
                break;
            }
            i++;
        }
        if(error == 1) {
            fprintf(stderr, "Please enter something containing only lower-case letters\n");
        }
    }
}

节目环节

Enter the word: hello world
Enter the word: Hello world
Please enter something containing only lower-case letters
Enter the word: hello World
Please enter something containing only lower-case letters
Enter the word: hello, world!
Enter the word:
Exiting the program

关于c - 有没有办法检查数组中字符串的大写和 isalpha 大小写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55781957/

相关文章:

c - C 中释放分配内存的问题

Python有条件地求解延迟微分方程

C - 解析带有未知数量参数的命令行

c - 在C中用另一个字母替换一个字母

c - VSCode C/C++ 扩展使用命令 process launch -i filename 运行调试器 gdb

c++ - "error: ' = ' : left operand must be l-value"? (在三元中使用赋值时?:)

c - timer_settime 在 uClinux 上的 pthread 中调用处理函数

c - 给定一个数字列表,查找输入某个数字的第一次和最后一次

c - OpenSSL i2d_ECPrivateKey() 崩溃

c - VS2005+WinSock : warning C4018: '<' : signed/unsigned mismatch