I'm currently working on some code and I know there's something wrong with it. My code prompts the user to input a name and it stores this as a string using the fgets () or sscanf ()
. If the user inputs something wrong (that is, numbers or alphanumeric cases) it should print the error message and ask for an input again until the user enters the input right. Also I've initialized:
char name [47];
printf ( "Name: " );
//some code dealing with newline character with the use of fgets
if ( (sscanf (name, %s, name)) == 1 )
//some code dealing with this condition
else {
do {
printf ( "ERROR: Invalid name. Name should consist of letters only.\n" );
printf ( "Name: " );
if (fgets ( name, sizeof (name), stdin ) == '\0' )
//some code dealing with EOF
} while ((sscanf (name, %s, name)) != 1);
}
Can anyone tell me what's wrong?
char name[47];
char line[4096];
while (printf("Name: ") > 0 && fgets(line, sizeof(line), stdin) != 0)
{
if (sscanf(line, "%46s", name) != 1)
...empty line?...
else if (valid_name(name))
break;
printf("Error: invalid name (%s). Name should consist of letters only.\n", name);
}
You forgot that printf()
returns the number of characters it prints? Well, most people don't test its result very often, but it is useful to do so in this context. The test could be != 6
instead of just > 0
, but either is likely to work OK in practice.
Note the use of "%46s"
to read a value into name
without risk of buffer overflow. Note, too, that sscanf()
won't read the newline into name
.