1

I've been trying to make a small program for someone who is about to have their birthday and well, sadly I'm stuck in the first part, I insert

#include <stdio.h>
#include <stdlib.h>

int main(){
    char name[10];
    printf("Please enter your name. \n");
    scanf("%s", &name);
    if(name=='Mariana'){
        printf("Hello Onee-sama");
    }
    else if(name=='David'){
        printf("Im sure you're not my master");
    }
    else{
        printf("Sorry, you are not authorized");
    }
}

(I plead you ignore the abnormalities) and When i run it, whatever name I insert, it gives me the else response. I would really appreciate help :)

2 Answers2

1

The code KopKoder wrote works perfect. Just adding explanation as to why strcmp or strncmp has to be used and not '==' operator. C strings are actually char arrays or pointer to char, which means that comparing a pointer to a const array will always give unexpected results. The link below gives better explanation to your question.

C String -- Using Equality Operator == for comparing two strings for equality

Community
  • 1
  • 1
zealouscoder
  • 96
  • 2
  • 3
  • 13
0

You just need to use strcmp to compare C char arrays. Here is your code modified. Hope this helps!

#include <stdio.h>
#include <stdlib.h>

int main(){
    char name[10];
    printf("Please enter your name. \n");
    scanf("%s", &name);
    if( (strcmp(name,"Mariana")) == 0){
        printf("Hello Onee-sama");
    }
    else if((strcmp(name,"David"))==0){
        printf("Im sure you're not my master");
    }
    else{
       printf("Sorry, you are not authorized");
    }
}
TheTotalJim
  • 67
  • 2
  • 13
  • `scanf("%s", &name);` is as good as coding `gets()`. Neither make for a quality answer. `scanf("%9s", &name);` would be better . `fgets()` then handling the `'\n'` would even be better. – chux - Reinstate Monica Dec 06 '16 at 03:02