如何在 C 中比较文本文件中的字符?

问题描述 投票:0回答:3

我希望能够执行检查,其中我将输入文件的第一个字符与某个字符进行比较(在本例中假设为

*
),然后如果它们不匹配则打印“Hello world”。 我可以从文件中读入。但是

strcmp()

不允许我比较输入文件字符和我声明的字符。

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

    char c;
    char compare[] = "*"

    do 
    {
        c = fgetc(file);
        compare = strcmp(c,compare); //Something is wrong here I think.
        printf("result: %d \n", compare);
    }
    while (c != EOF);
    fclose(file);
    return 0;
}


c compare text-files
3个回答
4
投票
until

它们之间存在差异或两个字符串同时以空字符终止。 如果你想比较两个字符你想要做的就是直接比较两个字符

char * string1 = "string1"; char * string2 = "string2"; if (string1[0] != string2[0]) puts("hello world");

或者你的情况

if (c != compare[0]) puts("hello world");

但是因为你的比较只是一个字符,而你只想比较 1 个字符,所以你最好将它声明为一个字符,比如通过做

char compare = '*'; ... if (c != compare) puts("hello world");



1
投票

#include <stdio.h> int main(void) { FILE *file = fopen("text.txt", "r"); char c; char compare = '*'; do { c = fgetc(file); if(c == compare) printf("result: %c \n", compare); } while (c != EOF); fclose(file); return 0; }



0
投票
strcmp

比较两个字符串。 您正在尝试将单个字符与空终止字符串

"*"
进行比较。我什至不确定您发布的这段代码是否会编译,因为
strcmp
需要两个
char *
作为参数,但您传递的是
char
作为第一个参数。

此外,您期望

strcmp

的返回值到字符指针,但是

strcmp
返回一个
int
.

这里是对

strcmp

的参考。如果您不确定某个标准库函数,您应该使用这个网站。但是,在这种情况下,我敦促您找到一个不同的、更简单的解决方案来解决您的问题(提示:strcmp 不需要比较

char
s),并练习阅读编译器警告/错误!
    

© www.soinside.com 2019 - 2024. All rights reserved.