c - Q : How to compare char from text file in C?

标签 c compare text-files

所以我希望能够执行检查,将输入文件的第一个字符与某个字符(在本例中假设为 *)进行比较,如果不匹配则打印“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;
}

最佳答案

strcmp 不比较字符,它是一个比较两个字符数组的循环直到它们之间存在差异或两个字符串同时以空字符终止。

如果你想比较两个字符你想要做的就是直接比较两个字符

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");

关于c - Q : How to compare char from text file in C?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39949502/

相关文章:

c - 如何从 ( C ) 中的另一个字符串获取子字符串

python - 通过 ctypes 从 Python 调用的 C 函数返回不正确的值

c - 为什么这提示有一个额外的操作数?

c++ - 对于 C++ 中的次要或相等条件

C++ 安全高效地将 std::weak_ordering 转换为 int

c# - 应使用哪种数据结构从文本文件中读取和存储大约 500 万个条目

java - 如何将文本文件中的特定行获取到数组列表中?

c# - 将 C 公式转换为 C#

c - 计算行数的最快方法?

php - 将文本文件的每一行读取到新的数组元素