jjyj
jjyj

Reputation: 459

How to compare char from text file in C?

I want to be able to perform a check wherein I compare the first character of the input file to a certain character (let’s say * in this case) and then print "Hello world" if they do not match.

I am able to read in from the file. But strcmp() is not letting me compare the input file character and my declared character.

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;
}

Upvotes: 0

Views: 3769

Answers (3)

Saaur
Saaur

Reputation: 31

The function strcmp compares two strings. You are trying to compare a single character to the null terminated string "*". I am not even sure if this code you have posted will compile, as strcmp takes two char *'s as parameters, yet you are passing a char as the first argument.

Additionally, you are expecting the return value of strcmp to a character pointer, but strcmp returns an int.

Here is a reference on strcmp. If you are ever unsure about a standard library function, you should use this website. However, in this case, I urge you to find a different, simpler solution to your problem (hint: strcmp is unnecessary to compare chars), and practice reading compiler warnings/errors!

Upvotes: 0

James Deng
James Deng

Reputation: 162

strcmp does not compare a character, it's a loop that compares two character arrays until there's a difference between them or both strings terminate with the null character at the same time.

if you want to compare two characters what you want to do is compare the two chars directly as in

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

or in your case

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

but since your compare is only one character and you want to only compare 1 character anyways you would be better off just declaring it as a char such as by doing

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

Upvotes: 4

Claude
Claude

Reputation: 11

You could do something like that instead (it's just to give you an idea) :

#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;
    }

Upvotes: 1

Related Questions