Strcmp in C Not Working -


i new c , having trouble program below. asks people if or not , displays message accordingly. far have tried using !strcmp, strcmp , strncmp , none returns positive value if, skip else statement. can 1 point me going wrong syntax seems fine me.

#include "stdafx.h" #include <stdio.h> #include <string.h>  int main() {    char well[3];     printf("hello, today? (yes/no) ");    scanf_s ("%s",well);        if (!strcmp(well,"yes")){            printf("glad hear it, i\n");    }    else{        printf("sorry hear that, hope day gets better\n");    }    system("pause");    return 0; } 

many all answers unfortunately none of them seem work. assigning 4 take account of null makes no difference. invoking scanf rather scanf_s results in access violation (which odd rest of program uses plain scanf. adding '4' parameter scanf_s makes no difference. tearing hair out here i'm happy accommodate null @ end of line program won't seem recognise it.

the string "yes" includes null terminator , looks {'y', 'e', 's', '\0'} in memory. therefore requires 4 chars can't safely read 3-element char array should give well @ least 4 elements

char well[4]; 

or, suggested lundin

#define max_response (sizeof("yes")) char well[max_response]; 

paxdiablo has explained you're not invoking sscanf_s correctly. 1 possible fix here switch calling scanf, passing max string size , checking user input

while (scanf(" %3s", well) != 1); 

of, sticking scanf_s

while (scanf_s(" %s", well, sizeof(well)-1) != 1); 

Comments