检查文件是否只有 C 语言的字母字符

标签 c

运行命令序列:

gcc -Wall main.c -o a.out

./a.out < inputfile.txt

我想从 ./a.out < inputfile.txt 这样的文件中读取内容并在逐个字符迭代后,如果所有字符都是字母数字,则打印“OK”,否则打印“ERROR”。我似乎无法让它发挥作用。

输入文件.txt

the brown fox jumped over the dog

this is another string

here is another string

main.c

int main() {

char c;

while (!feof(stdin)) {
    c = getchar();
    if (!isalnum(c)) {
        printf("ERROR!\n");
        
        exit(1);
    }
    }
printf("OK\n);

return 0;
}

最佳答案

正如其他人所说 - 空格和换行符不是数字字符。在这种情况下,请使用 isalnum() + isspace() 。除此之外,考虑使用某种标志而不是使用 exit() 函数:

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

int main()
{
    int c;
    char ok='Y';

    while(c = getchar())
    {
        if(c == EOF) break;

        if(!isalnum(c) && !isspace(c))
        {
            ok = 'N';
            break;
        }
    }

    printf("%c\n", ok);
    return 0;
}

RTFM:http://www.cplusplus.com/reference/cctype/
我发誓这是我最后一次帮助那些甚至无法调试代码的人。

关于检查文件是否只有 C 语言的字母字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32340422/

相关文章:

在 C 中导致段错误 |堆栈虚拟内存

c - 从标准输入读取命令行参数

c - 链表数组在 C 中无法正常工作

perror() 的 C++ 替代方案

c - 在不更改 API 且未收到警告的情况下将 const char* 转换为 char* 的正确方法是什么

C Structure post increment 将结构增加 4 个字节?为什么是这样?

c - 过滤链表并返回新的链表 C

c - 循环链表中的多项式

c - 动态数组的大小

c - 通过中断检测热插拔