How to compare words on C -


i have no idea why code not working. please me? (i want simple version-fix if it's possible, because i've started study c couple of weeks ago.)

#include <stdio.h> #include <string.h>   int main () {     char *name="alina";     char *input;     printf ("what's name? \n");     scanf ("%s",&input);     if (input=="alina")         printf("your name %s job!\n ",&name);     if (input!="alina")         printf("are sure? open program again , insert correct name");     while (1); } 

you did errors. first, if want insert string, can use %s, have use array of char in can store string. that's, have write this.

char input[100]; scanf("%s", input); 

and it'll work. snippet of code means: need insert (store) string. first create place in can store (pay attention string must maximum of 99 characters; array has size 100, last character used represent end of string), , use scanf write want.

the second error if want compare 2 strings, can't use == or !=, when numbers. string.h library lets use strcmp function, this:

if (strcmp(name, input) == 0)   // means strings equal    ... else    ... 

remembering that

char* name = "alina"; char input[100]; 

eventually, here you're inspected version of code:

#include <stdio.h> #include <string.h>  int main() {      char* name = "alina";     char input[100];     printf("what's name?\n");     scanf("%s", input);     if (strcmp(name, input) == 0)         printf("your name %s job!\n", name);     else         printf("are sure? open program again , insert correct name\n");      return 0; } 

the while(1) @ end of code absolutely dangerous, because starts infinite loop never ends, crashing program. want remove it!


Comments

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -