-7

I am just starting to learn C coding ,I am trying to write a program that keeps scanning names and once it scans a specific name lets say for example "John" it stops Please correct me

#include <stdio.h>
int main()
{
    char name[20];
    printf("enter a name:");
    for(;;)
    {
        scanf("%s",name);
        if (name='John')
        {
            break;
        }

    }
    
Ken Y-N
  • 14,644
  • 21
  • 71
  • 114
  • First of all, you are not comparing `name` to "John", you are assigning it. And second, using the `==` operator on two string pointers is not going to compare the contents of the strings. – jkb Jun 24 '21 at 23:27
  • 1
    Saw this question already once today. Y'all should team up. – user4581301 Jun 24 '21 at 23:28
  • You already asked this exact [same question](https://stackoverflow.com/questions/68123015/need-help-in-c-to-stop-the-loop-once-you-input-a-specific-name) today (now deleted). And you have already been pointed to the duplicate post that shows you the correct way to compare strings. Why are you asking the same question again and why are you not acting on the info already given to you? – kaylum Jun 24 '21 at 23:31
  • OK. Well, if you can't team up with yourself who can you? – user4581301 Jun 24 '21 at 23:48
  • it is either `int main(void)` or `int main(int argc, char **argv)`. Don't use `"%s"` with `scanf`. At least give a max length: `"%19s"`. `'John'` is an integer of implementation defined value, not a string. `"John"` is a string. `=` is assignment, not the comparison operator `==`. But then `==` doesn't say if to strings are equal, only if they are stored in the same memory location. Use `strcmp` for string comparison. And always compile with `-Wall`. The compiler could then have told you some of this. – HAL9000 Jun 25 '21 at 00:47

1 Answers1

0

You can't compare two string pointers with != or ==. you need to use strcmp, for example:

while (strcmp(check,input) != 0)

strcmp compares the string pointed to, by str1 to the string pointed to by str2.