Reputation: 2060
I am trying to compare contents of char* to a string. I am able to print out the content but not able to compare them.
#include<stdio.h>
int input(char * x){
int i,j = 0;
char myArray[10];
x = myArray;
scanf("%s", x);
for(x; *x !='\0'; x++){
if(*x == "ne"){
printf("%d",1);
return 0;
}
}
}
Upvotes: 0
Views: 775
Reputation: 153557
OP's code nicely iterates through x
...
for(x; *x !='\0'; x++){
... but then attempts to compare each char
of x
to the address of "ne"
.
if(*x == "ne"){ // bad code
To compare the strings pointed by 2 char *
, could make your own strcmp()
.
Note the real strcmp()
returns 0 when strings match or positive or negative values depending on which is "greater". OP's seems to only need an equal or not comparison.
// Return 1 if the same
int my_streq(const char *s1, const char *s2) {
while (*s1 == *s2 && *s1) {
s1++;
s2++;
}
return *s1 == *s2;
}
int readinput(char * x) {
....
if (my_streq(x, "ne")) {
printf("%d",1);
return 0;
}
....
}
Upvotes: 2