且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C 检查用户输入错误

更新时间:2023-11-26 11:03:10

如果用户输入超过 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';
 }