#include <stdio.h>
#include <string.h>
#define N 5
char username[N+3][20]={"ana","sofia","maria","isabel","joao","hugo","francisco","pedro"};
char str[20];
read_username()
{
printf("Insert your username: ");
gets(str);
}
void searchusername(int n)
{
int i;
for(i=0;i<=n;i++)
{
if(strstr(username[i], str) != NULL)
printf("username exists")
}
}
int main()
{
read_username();
searchusername(8);
}
I have the code to check if username exists, but i can´t seem to turn it around so i only get the printf when username doesn't exist, any other way without using NULL is also okay, ty.
One issue is that you are not avoiding a buffer overflow with gets()
. I have to assume for this example that you are typing in short usernames that do not exceed 19 characters. Anything longer is going to cause problems if you don't account for it.
More importantly, you are not comparing the usernames correctly. You should not be using strstr()
for that purpose. It searches for a substring inside of another string, it does not compare strings. For example, if you typed in ia
, strstr()
would match with both sofia
and maria
, both of which are wrong results for a username lookup. Use strcmp()
for comparisons.
Try something more like this instead:
#include <stdio.h>
#include <string.h>
#define N 8
char* username[N] = {"ana", "sofia", "maria", "isabel", "joao", "hugo", "francisco", "pedro"};
char str[20] = {0};
void read_username()
{
printf("Insert your username: ");
if (fgets(str, 20, stdin))
{
int len = strlen(str);
if ((len > 0) && (str[len-1] == '\n'))
str[len-1] = '\0';
}
}
void searchusername()
{
for(int i = 0; i < N ; i++)
{
if (strcmp(username[i], str) == 0)
{
printf("username exists");
return;
}
}
printf("username does not exist");
}
int main()
{
read_username();
searchusername();
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments