C 检查用户输入错误 [英] C check user input error

查看:43
本文介绍了C 检查用户输入错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要做的就是要求输入密码并在输入超过 10 个字符时打印出错误消息.如果第一个输入短于 10 个字符,它会起作用.它只是打印出输入并退出程序.如果输入的长度超过 10 个字符,则会打印错误消息并要求输入新密码,但如果第二次输入的字符少于 10 个字符,则会打印出输入,然后程序会以Thread:1"信号中断SIGABRT"错误.我知道我不应该使用 get,但我正在尝试找到一种方法来使用它使我的代码工作.

All I am trying to do is ask for a password and print out an error message if the input is longer than 10 characters. It works if the first input is shorter than 10 characters. It just prints out the input and exits the program. If the input is longer than 10 characters the error message prints and it asks for a new password, but if the input is less than 10 characters on the second try it prints out the input and then the program breaks with a "Thread:1 signal SIGABRT" error. I know that I shouldn't be using gets, but I am trying to find a way to make my code work using it.

#include <stdio.h>

#define BUFFER_LENGTH   11

int main() {
    int cont;
    while (1) {
        char line[BUFFER_LENGTH];
        char *p;
        printf("Enter Password: ");
        p = gets (line);
        if (strlen(p)>10) {
            printf("Error! Password must be shorter than 10 characters! \n");
        }else{
            printf(p);
            printf("\n");
            break;
        }
    }
}

推荐答案

如果用户输入超过 10 个字符,您最终会使用超出有效限制的内存.这正是您必须避免使用 gets 的原因.请参阅为什么是gets函数如此危险以至于不应该使用它? 有关该主题的更多信息.

If user input is longer than 10 characters, you end up using memory beyond the valid limits. That's exactly the reason you MUST avoid using gets. See Why is the gets function so dangerous that it should not be used? for more info on the subject.

gets 行更改为:

fgets(line, sizeof(line), stdin);

然后,您不必担心用户输入超过 10 个字符.它们将被简单地忽略.

Then, you don't have to worry about the user entering more than 10 characters. They will be simply ignored.

如果您想将该用例作为用户错误处理,请更改 line 的大小,但仍使用 fgets.

If you want to deal with that use case as a user error, change the size of line but still use fgets.

更新,感谢@chux

如果用户输入的字符少于您的案例中的 11 个字符,则该行

If the user enters less than the 11 characters in your case, the line

 fgets(line, sizeof(line), stdin);

不仅会读取字符,还会在其中包含结束的换行符.您必须添加一些代码来修剪 line 中的换行符.

will not only read the characters, it will also include the ending newline character in it. You'll have to add a bit of code to trim the newline character from line.

 // Trim the newline character from user input.
 size_t len = strlen(line);
 if ( len > 0 && line[len-1] == '\n' )
 {
    line[len-1] = '\0';
 }

这篇关于C 检查用户输入错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆