I am new to C and I am currently dealing with array functions.
There is my problem, I am asking user to input his username, and I would like to allow number, char, and space as first character. So I created a function to prevent user from just typing spaces using a do-while loop. At the first iteration, if I only 4 spaces type the 'filter' works perfectly, but if I type 4 spaces again, the function considerer thoses spaces as good. Here is the code:
void user_name (char *name) {
int nb_space = 0;
char buffer;
do {
printf("Player, please type your username \n");
memset(name,'\0', sizeof(*name));
scanf("%99[^\n]", name);// Using REGEX to prevent buffer issues with '\n'
for(int i=0;i< sizeof(name);i++){
if (name[i] == (char) ' '){
nb_space++;
}
}
while ((buffer = (char) getchar()) != '\n' ? buffer != EOF : false);//Using 'getchar' to empty the buffer
} while (nb_space == strlen(name));//I tryed to replace strlen with sizeof but nothing have changed
first_maj(name);
}
And there is the caller:
int main(int argc, char** argv){
char name[100];
user_name(name);
printf("your name: %s\n",name);//to check what we got
}
The "first_maj" function is just a fonction which capitalizes the first char of each separated word. This is the output I got (I represente the spaces with '.':
Player, please type your username
....
Player, please type your username
....
your name: ....
The program should asks again and again until the user types a character after the 4 spaces, or simply types directly characters. Exemple of wished output (dots = spaces):
Player, please type your username
.....
Player, please type your username
...john.rambo
your name: ...John.Rambo
Where is my mistake ? I could not figure out what is wrong in this code.
EDIT #1
Here is the capitalize function "first_maj" if it is important to find my mistake:
void first_maj (char name[]){
if (isalpha(name[0])){
name[0]= (char) toupper(name[0]);
}
for(int i=1;i<strlen(name);i++){
if (isalpha(name[i]) && name[i-1] == ' '){
name[i] = (char) toupper(name[i]);
}
}
}
EDIT #2
My question was about the iteration issue, not exactly the size of the array, but thank to you i could realize about other mistake. After reviewing the code with the debug function, i finally found the mistake I was looking for: I just forgot to reinitialize nb_space within the loop:
void user_name (char *name, int length) {
int nb_space;
char buffer;
do {
nb_space = 0;
printf("Player, please type your username \n");
memset(name,'\0', sizeof(*name));
scanf("%99[^\n]", name);// Using REGEX to prevent buffer issues with '\n'
for(int i=0;i< sizeof(name);i++){
if (name[i] == (char) ' '){
nb_space++;
}
}
while ((buffer = (char) getchar()) != '\n' ? buffer != EOF : false);//Using 'getchar' to empty the buffer
} while (nb_space == strlen(name));//I tryed to replace strlen with sizeof but nothing have changed
first_maj(name);
}