-4

This code will not run. Can somebody tell me why?

#include <stdio.h>
#include <string.h>
main (){
    char user[7];  
    printf("Username\n");
    scanf("%s",user);
    if(user == 'admin'){
        printf("Hello World");
    }else{
        printf("Bad");
    }
    return(0);
}
Peyman Mohamadpour
  • 17,954
  • 24
  • 89
  • 100
WILEY
  • 3
  • 1

2 Answers2

1

This is a working example. You need to use strcmp to compare strings. strcmp() returns 0, if the strings are equal.
If the max input length is known, then you should also use length specifier in scanf or one of the suggestion listed here, to prevent a buffer overflow.

#include <stdio.h>
#include <string.h>

int main(int argc, char* argv)
{
    char user[7];  
    printf("Username:\n");
    scanf("%6s", user);

    if(!strcmp(user, "admin"))
    {
        printf("Hello World");
    }
    else
    {
        printf("Bad");
    }

    return 0;
}
Community
  • 1
  • 1
tambre
  • 4,625
  • 4
  • 42
  • 55
0

This is not working because you are comparing two strings the wrong way. You need to use strcmp. Check this answer to see what strcmp returns in C.

To make your program work, change the line

if (user == 'admin')

to

if (strcmp (user, "admin") == 0)

Also, using scanf might be a bit dangerous, in rare cases. I prefer using fgets for strings. To use fgets, do:

fgets (user, sizeof (user), stdin);
Community
  • 1
  • 1
Box Box Box Box
  • 5,094
  • 10
  • 49
  • 67