1

Why do I get format '%s' expects argument of type 'char*'? How should I fix the problem?

Here are my codes:

char UserName[] = "iluvcake";
scanf("%s", &UserName);
printf("Please enter your password: \n");
char PassWord[] = "Chocolate";
scanf("%s", &PassWord);
    //if...else statement to test if the input is the correct username. 
    if (UserName == "iluvcake") 
    {
     if (PassWord == "Chocolate"){
     printf("Welcome!\n");
    }
    }else
    {
     printf("The user name or password you entered is invalid.\n");
    }
2
  • 1
    Because name of an array is also an address. Do scanf("%s", UserName); instead of scanf("%s", &UserName); Commented Apr 3, 2013 at 14:51
  • 1
    I know this is not your question, but I simply cannot resist. Dealing with passwords you should always: Turn echo off so the password is not shown during typing, erase the password from memory as soon as you don't need it anymore (overwrite it with 0's) and not hardcode it into your code (use hashes instead). If you put the password into the code it is nealry like putting it into a textfile. Commented Apr 3, 2013 at 14:55

4 Answers 4

4

&UserName is a pointer to an array of char (i.e., a char**). You should use

scanf( "%s", UserName );
Sign up to request clarification or add additional context in comments.

1 Comment

Not char** but char (*)[9].
2
  1. scanf for %s takes a char array/pointer, not pointer to it. drop the & from the scanf statements.
  2. You cannot compare strings with ==. Use strcmp.

Comments

0

Must be

scanf("%s", UserName);
scanf("%s", PassWord);

because UserName and PassWord are pointers to char arrays.

Comments

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

main(){
char name[20];
char password[10];
printf("Enter username: ");
scanf("%s",name);
printf("Enter password: ");
scanf("%s",password);
if (strcmp(name, "Admin") == 0 && strcmp(password, "pass") == 0)
printf("Access granted\n");
else printf("Access denied\n");


getch();
}

:)

1 Comment

Nice working example! it addresses the question. However would you please edit the answer and light on the problem. here is a link stackoverflow.com/help/how-to-answer

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.