How to compare strings in C?


The while tells me that the comparison does not exist

#include <stdio.h>

int main() { 
    int n, e, op, edad; 
    char sexo[1], res[2]; 
    n = 0; 
    edad = 0; 
    do {
        n = n + 1; 
        printf("Edad del conductor\n"); 
        scanf("%d", &e); 
        printf("Sexo de conductor F= femenino, M= masculino\n"); 
        scanf("%s", sexo); 
        printf("1 si es capital y 2 otra parte del estado\n"); 
        scanf("%d", &op);

        if (edad < 30) {
            edad = edad + e;
        printf("desea ingresar otro usuario? Si o No?\n");
        scanf("%s", res);
    } while (res != "No");

    edad = edad / n;
    printf("%d", edad);

    return 0; 


What happens is that in C you cannot compare strings using the == or != Operators, these will only compare the pointers of both.

You must use a function to compare like strcmp

#include <string.h>

// ...

} while (strcmp(res, "No") != 0)

The function returns 0 when they are equal.

From your comments, if you need to manipulate a single character then you don't need to use string functions and you could change your program to something like this:

char res;

// ...
    printf("desea ingresar otro usuario? (S)i o (N)o?\n");
    scanf(" %c", &res); // hay un espacio en blanco antes de %c para que no capture el "enter" anterior
} while (res != 'N');

Notice that now res is declared as char sin [] . scanf now uses the %c format to read a single character and 'N' uses single quotes ' no " to indicate that it is not a string.

Scroll to Top