How should I compare strings correctly in C?

I’m building a simple C program that asks the user to input a word or character, stores it, and keeps printing it until the user types the same input again to exit.

However, even when the user retypes the original input, the loop doesn’t stop.

Am I using the wrong method for string comparison in C? I’m aware that using check != input may not be the correct approach, but I’m unsure how to properly handle this.

Any advice on how to string compare in C the right way?

@Asheenaraghununan You’re right, check != input isn’t the way to go in C.

That just compares memory addresses, not the actual string contents.

If you want to compare the actual characters, use strcmp(check, input) == 0. It returns 0 when the strings are equal.

So your while loop should look like while (strcmp(check, input) != 0).

That’ll do exactly what you’re aiming for!

I ran into this exact issue back when I was learning C.

It’s a common pitfall! Since strings in C are arrays of characters, comparing them with == or != just checks if they point to the same memory location.

Use strcmp() from string.h instead, it checks the content of both strings.

So just replace your condition with strcmp(check, input) != 0, and it’ll work perfectly.

Classic C gotcha! In C, check != input doesn’t compare the actual strings—it’s comparing the addresses in memory.

To properly handle string compare in C, include <string.h> and use strcmp(). Your loop should be: while (strcmp(check, input) != 0).

That way, it checks character-by-character if both strings match.