There is no string
data type in C programming language. Strings in C are represented as array of characters
.
In C, char
is a data type to represent a character. So, all you need to do is declare a array of char data type
to represent a string in C. Each element in that array will hold a character of your string.
Also, operators in C like ==, !=, +=, +
are defined for build-in data types
in C and since, there is no operator overloading in C, you can't use these operators with your C-String as C-Strings are not build-in data type in C programming language.
Note: C-Strings are actually Null-terminated array of char data types. That means, last character in any C-String in C will be used to store a Null Character ('\0')
which marks the end of the string.
The Header file <string.h>
has predefined functions that you can use to operate on C-String(Null-terminated array of char data type). You can read more about it over here.
So, your program should look like:
#include <stdio.h>
#include <string.h>
#define CSTR_MAX_LEN 100
int main()
{
char uname[CSTR_MAX_LEN+1]; //An extra position to store Null Character if 100 characters are to be stored in it.
char passwd[CSTR_MAX_LEN+1];
printf("Enter your username: ");
scanf("%s", uname);
printf("Enter your password: ");
scanf("%s", passwd);
// Use strcmp to compare values of two strings.
// If strcmp returns zero, the strings are 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, the correct format specifier to handle C-Strings are %s
in C programming language. So, i have to change your scanf()
function call. Also, i have used strcmp()
function which is declared in header file <string.h>
(i have included this header file in the above program). It returns numeric zero if strings match. You can read more about it above here. Also, have a look at strncmp()
which is safer version of strcmp()
. Also, remember that it can lead to undefined behavior
if you try to access any array out of it's bound. So, it would be good idea to include checking in your program. As, someone included in their answer you can change my scanf()
function call to:
scanf("%100s", uname);
It avoids to read more than 100 characters in array uname
as it is allocated only to store 100 characters(excluding the Null character).