while 循环中的 fgets

fgets inside the while loop

我遇到了 fgets 的问题,因为它在 k 输入后第一次进入 while 循环时返回 \n。 由于我已经在 while 循环中并且我的 #1 try 已经写好了,我该如何处理呢?

int main() {
    char r;

    printf("How to input?\n");
    printf("Keyboard ([K])\n File ([F])\n Leave ([E])\n");
    scanf("%c", &r);

    if (r == 'k' || r == 'K') {
        printf("\nKeyboard\n");
        opcaoTeclado();
    } else {
       // stuff
    }
}

void opcaoTeclado() {
    int try = 0;
    char inputline[161];

    while (try <= 10) {
        printf("\n#%d try\n ", try);
        fgets(inputline, 160, stdin);
        try++;
    }
}

调用 scanf() 后,输入中有一个换行符,由第一次调用 fgets() 读取。 fgets() 在遇到换行符时停止读取输入 \n。因此,它不读取任何输入。

scanf() 之后添加对 getchar(); 的调用以使用换行符。

或者如果输入中有多个字符,你也可以使用循环来消费。

int c;

while((c= getchar()) != '\n' && c != EOF); 

一般来说,最好避免将 scanf()fgets() 混用。您可以使用 fgets() 而不是 scanf() 并使用不太容易出现的 sscanf() 解析该行。

您应该清除标准输入缓冲区。您可以在循环之前使用 fflush(stdin); 来完成。但这是一种糟糕的风格。还考虑 fseek(stdin,0,SEEK_END);.

您只需在格式后添加 space 即可使用 \n

scanf("%c ", &r);
  1. I'm having an issue with fgets because it is returning \n on the first time it enters the while loop right after the "k" input.

    这是因为对于 scanf("%c", &r);,当您输入 k[ENTER_KEY] 时,字符 k 会存储在变量 r 中,留下 \n(按下 ENTER 键)在 stdin 流中。

    因此对于 fgets(inputline, 160, stdin);,它在 stdin 中找到 \n 换行符,将其存储在 inputline 中并从 man -s3 fgets 退出:

    fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer.


  1. Since I'm already inside the while loop and my "#1 try" as already been written, how do I deal with this?

    您可以使用 getchar()

  2. stdin 中消耗 \n