-
String compare problems
Hey guys
I am making a very simple string program to test logical operators and although this compiles its not giving the correct output.
Code:
#include <stdio.h>
#include <string.h>
int main ( void ) {
char username[ 15 ];
char password[ 20 ];
int flag = 0;
puts("Enter your username: ");
fgets( username, 15, stdin );
puts("Enter your password: ");
fgets( password, 20, stdin );
if (( strcmp( username, "peter") == 0 ) && ( strcmp( password, "willow") == 0)) {
puts("\nWelcome to the network!");
flag = 10;
}
if (( strcmp( username, "guest") == 0 ) || ( strcmp( password, "guest")) == 0 ) {
puts("\nGuest registration valid for 24hrs");
flag = 2;
}
if (!flag ) {
puts("\nInvalid input!");
}
return 0;
}
I keep getting "Invalid input returned when ever i compare the strings, can
anyone see what I am doing wrong?
Thank in advance guys.
-
You're not stripping the newlines from fgets() . . .
-
Thanks!
I forgot to add
Code:
username[ strlen(username ) -1 ]= 0;
Cheers Nightowl
-
Same thing for password, of course . . . :)
-
Quote:
Originally Posted by
swgh
I forgot to add
Code:
username[ strlen(username ) -1 ]= 0;
Cheers Nightowl
That will fail if the strlen() returns 0 - which would happen if someone enters CTRL-Z or CTRL-D depending on platform.
--
Mats
-
Use a "chomp" style function:
Code:
void chomp (char *line) {
int len=strlen(line);
if ((len>0) && (line[len-1]=='\n'))
line[len-1]='\0';
}
chomp(username);
chomp(password);