簡體   English   中英

Fgets-在循環中不起作用

[英]Fgets - doesn't work in the loop

問題在於,fgets在循環的第一次迭代中沒有任何值。 只是簡單地跳過它。 照我看來。 我的代碼中存在一些基本錯誤,但是我看不到。 Fgets僅在2d迭代中開始獲取值。

#include <stdio.h> 
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main(void) 
{
    int t;
    scanf("%i", &t);

    char ways[100];
    for (int j = 0; j <= t; t++)
    {
        fgets (ways, 100, stdin);
        printf("Ways = %s\n", ways);
    }

    return 0; 
 }`

解決問題的最簡單方法是使用fgets()sscanf()讀取初始數字。 另外,您的循環似乎有幾個錯誤。 您可能是說j < t而不是j <= t ,所以循環執行了t次。 此外,幾乎可以肯定,您打算增加j而不是t ,這將導致無限循環。

#include <stdio.h> 
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main(void) 
{
    int t;
    char buffer[100];
    fgets(buffer, 100, stdin);
    sscanf(buffer, "%i", &t);

    char ways[100];
    for (int j = 0; j < t; j++)
    {
        fgets (ways, 100, stdin);
        printf("Ways = %s\n", ways);
    }

    return 0; 
 }

請注意,在格式字符串的末尾添加空格字符通常是一個壞主意,因為這會導致scanf()繼續嘗試讀取輸入,直到遇到非空格字符,從而阻塞了輸入。

scanf()正在讀取uder輸入的數字,並將其尾隨空格和換行符保留在緩沖區中。 fgets()然后讀取這些內容,因此似乎在第一次迭代時讀取了一個空字符串。

要解決此問題,請在%i之后添加一個空格字符。 空格將空格與scanf匹配。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM