Reputation: 19
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 :)
Upvotes: 1
Views: 1615
Reputation: 94
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
Upvotes: 1
Reputation: 77
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");
}
}
Upvotes: 0