0

我目前正在编写一些代码,我知道它有问题。我的代码提示用户输入名称,并使用fgets () or sscanf (). 如果用户输入错误(即数字或字母数字大小写),它应该打印错误消息并再次要求输入,直到用户输入正确的输入。我也初始化了:

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);
}

谁能告诉我怎么了?

4

1 回答 1

1
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);
}

你忘了printf()返回它打印的字符数?好吧,大多数人不会经常测试它的结果,但在这种情况下这样做很有用。该测试可能!= 6不仅仅是> 0,但在实践中任何一个都可能正常工作。

请注意使用"%46s"将值读入name没有缓冲区溢出的风险。还要注意,这sscanf()不会将换行符读入name.

于 2013-08-27T04:32:04.940 回答