I am learning C and I am looking at some tutorials and I am now learning about while. In the video there was example of asking "what is your name?" and while is used there as a tool that when you try clicking enter it will say that you didn’t enter a name and would ask you for name again. But I had idea what if someone uses space instead of just clicking enter. So I tried to find the answer to it on here and other sites but I couldn’t find my exact problem and answer for it. I tried ctype.h library but it didnt work so I will show you code that worked but didn’t work as I wanted.
#include<stdio.h>
#include<string.h>
int main(){
char name[25];
printf("What is your name?\n");
fgets(name, 25, stdin);
name[strlen(name) - 1] = '\0';
while(strlen(name) == 0){
printf("You didn't insert your name!!!\n");
printf("What is your name?\n");
fgets(name, 25, stdin);
name[strlen(name) - 1] = '\0';
}
printf("Your name is %s" name);
return 0;
}
>Solution :
In your current code, the while loop checks whether the length of the input string is zero (which occurs when the user presses "Enter" without entering any characters), but it doesn’t handle the case where the user enters spaces instead of a name.
To handle this, you can modify the condition to check whether the entered name contains only spaces, or no characters at all. Here’s a solution using the isspace() function from the ctype.h library, which checks if a character is a whitespace character (spaces, tabs, etc.).
#include<stdio.h>
#include<string.h>
#include<ctype.h>
// Function to check if the input contains only spaces
int is_only_spaces(char *str) {
for (int i = 0; i < strlen(str); i++) {
if (!isspace(str[i])) {
return 0; // Found a non-space character
}
}
return 1; // String contains only spaces
}
int main() {
char name[25];
printf("What is your name?\n");
fgets(name, 25, stdin);
name[strlen(name) - 1] = '\0'; // Remove the newline character
// Loop until the name is not empty and not only spaces
while(strlen(name) == 0 || is_only_spaces(name)) {
printf("You didn't insert a valid name!!!\n");
printf("What is your name?\n");
fgets(name, 25, stdin);
name[strlen(name) - 1] = '\0'; // Remove the newline character
}
printf("Your name is %s\n", name);
return 0;
}