Search code examples
arrayscstringstring-comparison

How to get integer and string input using scanf?


I have a problem in C language

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

int main()
{
    char usrname[17] = "nsa-secret-agent";
    char password[9] = "marshal41";
    char usr[512], pass[512];

    printf("username: ");
    scanf("%[^\n]%*c", usr);
    printf("password: ");
    scanf("%[^\n]%*c", pass);
    printf("%s\n", usr);
    printf("%s\n", pass);

    if (strcmp(usrname, usr) == 0 && strcmp(password, pass) == 0){
        printf("You Have Successfully Logged In!\n");
    }

    else{
        printf("username or password not found!\n");
        exit(0);
    }

    return 0;
}

When I run this code it runs without any errors but when give input like below:

username: nsa-secret-agent
password: marshal41
nsa-secret-agent
marshal41
username or password not found!

I am giving correct credentials but still it's showing error


Solution

  • Your arrays for usrname and password are off by one:

    char usrname[17] = "nsa-secret-agent";
    char password[9] = "marshal41";
    

    These are short one byte for the zero terminator which makes the comparison later fail. Either add one or just use

    char usrname[] = "nsa-secret-agent";
    char password[] = "marshal41";
    

    or you could even use

    char *usrname = "nsa-secret-agent";
    char *password = "marshal41";
    

    since the strings are not modified.