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/