Page 1 of 1

problem with my scanpass function

Posted: Sat Nov 03, 2007 6:59 am
by mohammed
this code accept only four characters and then print the two phrases
you are %s
you are not mohammed
!!

Code: Select all

#include<stdio.h>
#include <conio.h>
main()
{
char name[10];
char name2[10]="mohammed";
char mypass[10];
char mypass2[10]="0123456789";

clrscr();
scanf("%s",&name);
scanpass(mypass[10]);
if(name[10]==name2[10] && mypass[10]==mypass2[10])
{
printf("hello %s",name);
}
else
{
printf("you are %s you are not mohammed",name);
}
getch();
}
scanpass(char pass[10])
{
int counter;
for(counter=0;counter<10;counter++)
{
pass[counter]=getch();
printf("*");
counter++;
}
return pass[10];
}

Posted: Sat Nov 03, 2007 7:18 am
by AndrewAPrice
Your program is flawed. Using C-style strings (a.k.a. array of chars) you must use strcmp, not the == operator.

Therefore, any username/password, as long as the 10th character of the username is null, and the 10th character of the password is 9, they should be able to log in. Also, you have a memory overflow with the password. The array is 10 characters wide, and you have provided a string 10 characters, and since strings are null terminated, the null character is being placed in the 11th element which does does not exist and is probably being used by another variable.

Also, when accepting strings as input, you should have a limit on the number of characters you can input (unless you're using C++ std::strings which are dynamically allocated) for the chance the someone is likely to have a username/password greater than 9 characters (the 10th character being the null-termination).

Posted: Sat Nov 03, 2007 10:37 am
by piranha

Code: Select all

name[10]==name2[10] && mypass[10]==mypass2[10]
I believe that this is comparing characters, for which you can use == operator.

However, why would you compare the 10th element in an array?
i believe the if statement should be:

Code: Select all

if(!strcmp(name, name2) && !strcmp(mypass, mypass2))
I am pretty sure of this. Because strcmp returns 0 if the strings are equal, then you have to ! both of them.

-JL

Posted: Sat Nov 03, 2007 10:53 am
by 01000101
or if all else fails.

Code: Select all

for(i=0;i<10;i++)
{ 
   if(name[i] == name2[i] && mypass[i] == mypass2[i]){}
   else{error_function();}
}

Posted: Sun Nov 04, 2007 6:25 am
by mohammed
thank you i will use strcmp