简体   繁体   English

C - 当输入超过fgets允许值时退出程序

[英]C - Program exits when input exceeds fgets allowance

I have the following program written in C: 我有以下用C编写的程序:

The main problem with this program is that if the input exceeds 80 characters when using fgets() function, the program just exits immediately. 该程序的主要问题是,如果在使用fgets()函数时输入超过80个字符,程序将立即退出。 The other code is executed, however it does not wait for the user to press enter. 执行其他代码,但不等待用户按Enter键。 It like simply ignores the getchar at the end. 它就像最后忽略了getchar一样。

How can I solve this problem please? 我该如何解决这个问题?

If the user input is longer than the 79 characters that fgets may read from stdin (it can read at most one less than its size parameter says, since it 0-terminates the buffer), the remaining input is left in the input buffer, hence the getchar() at the end immediately succeeds. 如果用户输入超过fgets可能从stdin读取的79个字符(它最多可以读取一个小于其大小参数的值,因为它0终止缓冲区),剩下的输入将保留在输入缓冲区中,因此最后的getchar()立即成功。

To avoid that, you need to clear the input buffer if the input was too long. 为避免这种情况,如果输入太长,则需要清除输入缓冲区。

The problem is that if the input was short enough, you don't know whether to clear the buffer or not. 问题是如果输入足够短,你不知道是否清除缓冲区。 So check whether you actually got a newline read in by fgets , 因此,请检查您是否确实通过fgets读取了换行符,

int len = strlen(password);
if (password[len-1] == '\n') {
    // got a newline, all input read, overwrite newline
    password[len-1] = 0;
} else {
    // no newline, input too long, clear buffer
    int ch;
    while ((ch = getchar()) != EOF && ch != '\n');
    if (ch == EOF) {
        // input error, stdin closed or corrupted, what now?
    }
}

Check if a new-line character was read by fgets() , and if not skip input until a new-line character is encountered: 检查fgets()是否读取了换行符,如果没有跳过输入,直到遇到换行符:

if (0 == strrchr(password, '\n'))
{
    /* Skip until new-line. */
    int c;
    while (EOF != (c = getchar()) && '\n' != c);
}

otherwise the call to getchar() will read what fgets() did not. 否则对getchar()的调用将读取fgets()没有的内容。

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

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