簡體   English   中英

while循環未按預期繼續

[英]The while loop doesn't continue as intended

由於某種原因,一旦我輸入要搜索的字符,main中的while循環就會終止,但目的是使您能夠輸入一行,然后輸入字符進行搜索,直到您輸入空白行(不輸入任何內容)。 基本上,我想無限地執行第1步和第2步,直到我什么都不鍵入然后按Enter鍵為止。 為什么不起作用? 謝謝任何人的幫助!

另外,還有一個小問題,輸入字符進行搜索后如何清除所有垃圾?

#include <stdio.h>
#define SIZE 41
int CharIsAt(char *pStr,char ch,int loc[],int mLoc);
int main(void){
    char array[SIZE],search;
    int found[SIZE],i,charsFound;
    //Step 1
    printf("Enter a line of text(empty line to quit): "); 
    while (fgets(array,SIZE, stdin)!=NULL && array[0]!='\n'){ //Loop until nothing is entered
    //Step 2
        printf("Enter a character to search: ");
        search=getchar();
        charsFound=CharIsAt(array,search,found,SIZE);
        printf("Entered text: ");
        fputs(array,stdout);
        printf("Character being searched for: %c\n",search);
        printf("Character found at %d location(s).\n",charsFound);
        for (i=0;i<charsFound;i++)
            printf("%c was found at %d\n",search,found[i]);
        printf("Enter a line of text(empty line to quit): ");
    }
    return 0;
}
int CharIsAt(char *pStr,char ch,int loc[],int mLoc){
    //Searches for ch in *pStr by incrementing a pointer to access
    //and compare each character in *pStr to ch.
    int i,x;
    for (i=0,x=0;i<mLoc;i++){
        if (*(pStr+i)==ch){
            //Stores index of ch's location to loc
            loc[x]=i;
            x++;    //Increment for each time ch was counted in pStr
        }
    }
    //Returns the number of times ch was found
    return x;
}

如果這不太令人討厭,我會包含整個代碼,如果可以的話,我可以嘗試制作一個更簡單的問題版本。 我認為發布整個代碼對於回答問題可能更有用。

再次感謝,加油!

   while (fgets(array,SIZE, stdin)!=NULL && array[0]!='\n'){
        printf("Enter a character to search: ");
        search=getchar();
        charsFound=CharIsAt(array,search,found,SIZE);
        printf("Entered text: ");
        fputs(array,stdout);
        printf("Character being searched for: %c\n",search);
        printf("Character found at %d location(s).\n",charsFound);
        for (i=0;i<charsFound;i++)
            printf("%c was found at %d\n",search,found[i]);
        if (fgets(array,SIZE, stdin)==NULL) break;
    }
    return 0;

這應該工作

發布代碼的主要問題是用戶必須按enter鍵才能將search字符輸入程序。 但是,對getchar()的調用僅消耗單個char,因此不消耗換行序列。

要解決此問題,請循環調用getchar() ,直到char為EOF或'\\ n'來清空任何/所有剩余垃圾的stdin

然后回到循環的頂部

暫無
暫無

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

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