tl;dr
int i=0;
User signed_up[k];
char input_user[15];
bool stop_cycle=false;
do {
printf("\n\n%*sUsername: ", 26, "");
fflush(stdin);
scanf("%s", input_user);
stop_cycle=true;
for (i=0;i<k;i++) {
if (strcmp(input_user, signed_up[i].username)==0) {
printf("\n%*sUsername inserito gi%c presente nel database!", 26, "", 133);
stop_cycle=false;
}
}
} while (!stop_cycle);
Longer Explanation
If this is your situation...
So you want to ask them to enter a username.
If the username exists, you want to ask them again (to enter a different username), and also print "Username inserito già presente nel database!"
You want to continue doing this until the user has entered a username that is not in the "database".
The purpose of the for
loop is to test whether the username (input_user
) is already in the "database" (i.e. the array, signed_up
).
The variable k
is a count of the number of User
objects in the signed_up
array.
Thus, the for
loop is looping through all the values in the signed_up
array to test whether input_user
matches a username
member of a User
object in the array.
If input_user
matches an existing username
of a User
, you want to continue looping in the do while
loop.
Setting stop_cycle
to true
will stop the loop.
Then...
Your problem is that you only want to set stop_cycle=false;
when input_user
matches a username
. That is the only time where you don't stop the cycle (i.e., stop_cycle=false;
)
The mistake is you put stop_cycle=false;
outside of the if
statement. It should be inside the if
statement. That will continue the "cycle" as long as the username already exists.
So this code works:
int i=0;
User signed_up[k];
char input_user[15];
bool stop_cycle=false;
do {
printf("\n\n%*sUsername: ", 26, "");
fflush(stdin);
scanf("%s", input_user);
stop_cycle=true;
for (i=0;i<k;i++) {
if (strcmp(input_user, signed_up[i].username)==0) {
printf("\n%*sUsername inserito gi%c presente nel database!", 26, "", 133);
stop_cycle=false;
}
}
} while (!stop_cycle);
Other Advice
In addition to other people's suggestions, my advice is:
Rename stop_cycle
to username_exists
, and k
to num_users
.
So the code looks like this:
int i=0;
User signed_up[num_users];
char input_user[15];
bool username_exists=false;
do {
printf("\n\n%*sUsername: ", 26, "");
fflush(stdin);
scanf("%s", input_user);
username_exists=false;
for (i=0;i<num_users;i++) {
if (strcmp(input_user, signed_up[i].username)==0) {
printf("\n%*sUsername inserito gi%c presente nel database!", 26, "", 133);
username_exists=true;
}
}
} while (username_exists);
This makes it clear that your for
loop is testing to see if the username exists, and it makes it clear that your do
loop will continue as long as the username exists. It also makes it clear that k
represents the number of users.