c - C中的字符问题

标签 c char compiler-errors fgetc

为什么不能编译?看不到错误

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

int main(void)
{
    char *c;
    FILE *f = fopen("file.txt", "r");

    if(f == NULL) {
        printf("Could not open file");
    }

    while((c = fgetc(f)) != EOF) {
        if(strcmp(c, " ") == 0) {
            printf(" ");
        } else if(strcmp(c, ":") == 0) {
            printf(":");
        } else if(strcmp(c, "@") == 0) {
            printf("@");
        } else if(strcmp(c, "\n") == 0) {
            printf("\n");
        } else {
            printf("Not a valid char");
    }
}

最佳答案

fgetc 以整数形式返回当前文件指针处的字符。

所以 char *c; 应该是 int c;

if(strcmp(c, " ") == 0) {

应该是

if(c == ' ') {

并类似地更改其他比较。

您可以将比较压缩为:

while((c = fgetc(f)) != EOF) {
    if(c == ' ' || c == ':' || c == '@' || c == '\n') {
        printf("%c",c);
    } else {
        printf("Not a valid char");
    }
}

关于c - C中的字符问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3752975/

相关文章:

c++ - 在 C++ 中连接不同类型的字符串

android - 构建错误 : Unable to find a particular resource

java - 如何快速初始化char二维数组?

java - 在编译器上编译成功的过程在在线编译器上失败了,为什么?

angular - 在Angular : Error encountered resolving symbol values statically中创建Redux存储时出错

c - 结构中成员的顺序重要吗?

c - 如何在 C 中的队列中存储 (x,y) 坐标

c - 程序过早离开循环

c - 竞态条件漏洞实验室

java - 如何从字符串中删除非 ASCII 字符?