簡體   English   中英

fgets()/ scanf()do-while循環

[英]fgets() / scanf() do-while loop

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

int main()
{

    char strA[10];

    int i, j;


    do {

        j = 0;

        memset(&strA,'\0', sizeof(strA));

        printf("Please enter your password: ");
        fgets (strA,10,stdin);

        printf("\n%s\n\n",strA);

        if (strlen(strA) > 8) {
            printf("That password is too long\n");
        }
        else {
            j++;
        }

    } while (j<1);
return 0;
}

你好。 我在dowhile循環中運行fgets() 我首先進行測試以查看輸入的字符串是否太長,如果字符串太長,則提示再次輸入該字符串(通過讓dowhile重新開始)。 問題在於,字符串的進位太長(從fgets()剪切下來的多余字符被設置為10)在第二,第三等等中輸入,而在dowhile循環的迭代中,直到最終剩下的的字符串滿足else語句,並且dowhile終止。 我需要dowhile循環的每次迭代都重新開始,在此手動輸入字符串。 有人可以幫忙嗎?

更換:

fgets (strA,10,stdin);

與:

scanf("%10s", strA);

同樣的問題。

嘗試這個

fgets (strA,10,stdin);
int c;                      // Notice that I declared c as int (getchar() returns int)
while((c = getchar()) != '\n' && c != EOF) // This will consume all the previous characters left in the buffer
    ;

暫無
暫無

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

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