Search code examples
cinputgetchar

comparing getchar with a character returns a warning and gives me the wrong code


i'm having a problem with comparisons using getchar() and file redirection.

I have a code that resembles this:

char result = getchar(); // getchar returns the next char in the file
int linecount = 0;

if (result == "\n") {
    linecount++;
}

But I get a warning when compiling it. It says that I can't compare an int with a pointer, but from my understanding, result is a char and so is "\n", so I'm really confused. I can also use printf("%c", result") and it works fine, implying that result is a char. Does anyone know why I'm getting this error? Thanks! Also, running the code, linecount will always return 0 even if the first character in the file I'm using as my input is a newline.


Solution

  • You are comparing a char with a char *, that is, a string. "" (doublequoted) values are treated as strings in C, so your code should be

    if (result == '\n') {
        linecount++;
    }
    

    Alternatively, you could use strcmp or strncmp with the char casted to a pointer, but that's not necessary.

    Do note that the size of a char is less than an int so the conversion from a char to int doesn't make you lose anything.