How do I deal with string input in C? -
i'm practicing c , make simple login program username , password... here code:
int main(){ char uname, passwd; printf("enter username: "); scanf("%c", uname); printf("enter password: "); scanf("%c", passwd); printf(" \n"); if (uname == "waw" && passwd == "wow"){ printf("you have logged in\n"); } else { printf("failed, please try again\n"); } return 0; }
and got error when try compile it
log.c: in function ‘main’: log.c:7:10: warning: format ‘%c’ expects argument of type ‘char *’, argument 2 has type ‘int’ [-wformat=] scanf("%c", uname); ^ log.c:9:10: warning: format ‘%c’ expects argument of type ‘char *’, argument 2 has type ‘int’ [-wformat=] scanf("%c", passwd); ^ log.c:13:14: warning: comparison between pointer , integer if (uname == "waw" && passwd == "wow"){ ^ log.c:13:33: warning: comparison between pointer , integer if (uname == "waw" && passwd == "wow"){ ^
there no string
data type in c programming language. strings in c represented array of characters
.
in c, char
data type represent character. so, need declare array of char data type
represent string in c. each element in array hold character of string.
also, operators in c ==, !=, +=, +
defined build-in data types
in c , since, there no operator overloading in c, can't use these operators c-string c-strings not build-in data type in c programming language.
note: c-strings null-terminated array of char data types. means, last character in c-string in c used store null character ('\0')
marks end of string.
the header file <string.h>
has predefined functions can use operate on c-string(null-terminated array of char data type). can read more on here.
so, program should like:
#include <stdio.h> #include <string.h> #define cstr_max_len 100 int main() { char uname[cstr_max_len+1]; //an position store null character if 100 characters stored in it. char passwd[cstr_max_len+1]; printf("enter username: "); scanf("%s", uname); printf("enter password: "); scanf("%s", passwd); // use strcmp compare values of 2 strings. // if strcmp returns zero, strings identical if ((strcmp(uname, "waw") == 0) && (strcmp(passwd, "wow") == 0)){ printf("you have logged in\n"); } else{ printf("failed, please try again\n"); } return 0; }
remember, correct format specifier handle c-strings %s
in c programming language. so, have change scanf()
function call. also, have used strcmp()
function declared in header file <string.h>
(i have included header file in above program). returns numeric 0 if strings match. can read more above here. also, have @ strncmp()
safer version of strcmp()
. also, remember can lead undefined behavior
if try access array out of it's bound. so, idea include checking in program. as, included in answer can change scanf()
function call to:
scanf("%100s", uname);
it avoids read more 100 characters in array uname
allocated store 100 characters(excluding null character).
Comments
Post a Comment