简体   繁体   English

我如何解决嵌套在if-else中的while循环?

[英]How can I fix this while loop nested in if-else?

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 () . 我的代码提示用户输入名称,并使用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? 您忘记了printf()返回它打印的字符数吗? 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. 测试可以是!= 6而不仅仅是> 0 ,但实际上两者都可以正常工作。

Note the use of "%46s" to read a value into name without risk of buffer overflow. 请注意,使用"%46s"将值读入name不会有缓冲区溢出的风险。 Note, too, that sscanf() won't read the newline into name . 还要注意, sscanf()不会将换行符读入name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM