I'm trying to make a loop that does not stop until the user inputs a string. For ex. if the user inputs a number or a letter it will say Invalid input
until the user enters a string.
But for some strange reason, when I run my code and I input a string, the program continues to loop the block of code. Here's the output
#include <stdio.h>
int main() {
char name[100];
char letter[100];
lt:
printf("\033[0;33m");
printf("\nEnter your Name:\ni.e. Miguel\n");
printf("\033[0m");
scanf("%s", name);
if (name != letter) {
printf("\033[0;31m");
printf("Invalid input");
printf("\033[0m");
goto lt;
}
return0;
}
I've tried the goto
function to loop the code but seems like that isn't working.
CodePudding user response:
Uninitialized variables:
char letter[100];
letter
is used uninitialized in your code. It's contents are indeterminate. Variables declared with automatic storage aren't implicitly initialised to 0.
Comparing strings:
if (name != letter)
This only compares the pointer addresses (and I believe it invokes undefined behavior), not the contents of the what those pointers point to.
The C standard library provides a function strcmp
that compares two strings.
Note: It's declared in string.h
.
Buffer overflow vulnerability:
scanf("%s", name);
is equivalent to using gets
. scanf
will happily continue to read input and potentially overflow the buffer.
Use a field width to limit input:
scanf("