1

I would like to know what is the problem with this code. I want to right a name in the programming and if it's correct give me "Let's go" if it's not give me go back. I want to add Zay in if statement through right it in scanf. but it gives me an error I searched a lot but there is a problem, pls help me.

#include <stdio.h>
int main()
{
char name[15];
printf("Type name ");
scanf("%s",&name);
if(name == 'zay')
{
printf("Let's go, %s\n", name);
}
else
{
printf("go back, %s\n", name);
}
return 0;}
zephryl
  • 14,633
  • 3
  • 11
  • 30
Haaland
  • 35
  • 6
  • 1) `'zay'` is not a string; 2) Strings are not compared with `==` – ForceBru Mar 08 '22 at 21:17
  • `if(name == 'zay')` does not do what you think it does. `man strcmp` – William Pursell Mar 08 '22 at 21:17
  • 1
    `scanf` is hard to use correctly and has many foibles. At the very least, you should *never* use a raw `%s`. Since `name` can only hold 15 characters and scanf writes what it reads plus a terminating null, you want to ensure that scanf does not read more than 14 characters. Use `%14s`. – William Pursell Mar 08 '22 at 21:19
  • 2
    @WilliamPursell - as an SO regular just let me say - I frkn hate scanf, tis evil and the cause of much pain to newcomers, and more experienced devs from time to time , but we are stuck with it :-( – pm100 Mar 08 '22 at 21:22
  • @pm100: Well, there is `fgets`. – Fred Larson Mar 08 '22 at 21:24
  • 1
    @FredLarson yup, I never use scanf, get a line and parse it for me every time , too much hidden logic inside scanf – pm100 Mar 08 '22 at 21:27
  • 2
    @pm100 I suppose it is easier for people teaching C to just teach `scanf` as a all-round input function even though it is exact opposite of its design purposes, instead of `fgets` and then `strtol` or `sscanf`. And then you end up with half of the C related questions being about `scanf`... – aulven Mar 08 '22 at 21:30
  • Thank you very much guys. I already started looking for fgets and strtol. you are the best :) – Haaland Mar 08 '22 at 21:39

1 Answers1

1

This is wrong

if(name == 'zay')

you mean

if(strcmp(name, "zap") == 0)

see https://man7.org/linux/man-pages/man3/strcmp.3.html

and you need to include string.h

pm100
  • 48,078
  • 23
  • 82
  • 145