簡體   English   中英

如何在C中多次運行循環?

[英]How to run through a loop multiple times in C?

好的,我修改了我的代碼,但是當用戶輸入 0 時無法讓它中斷。我嘗試了 0、'0' 和“0”,但都沒有中斷循環。

#include <stdio.h>
#include<conio.h>

int main(){
int word;
int countword = 0;
int countpunct = 0;
do{
    printf("\nEnter the String: ");
    while ((word = getchar()) != EOF && word != '\n'){
        if (word == ' ' || word == '.' || word == '?' || word == '!' || word == '(' || word == ')' || word == '*' || word == '&'){
            countword++;
        }
        if (word == '.' || word == '?' || word == '!' || word == '(' || word == ')' || word == '*' || word == '&'){
            countpunct++;
        }
    }
    printf("\nThe number of words is %d.", countword);

    printf("\nThe number of punctuation marks is %d.", countpunct);

} while (word!= 0);

}

wordEOF\\n時,您的內部循環會中斷。 由於到達外循環結束時您永遠不會修改它,因此條件將始終為真。

回到你的預編輯代碼,你真正需要的是改變scanf("%c", word); scanf("%c", &word); ,盡管您應該為此使用單獨的char變量,因為%c格式說明符需要一個指向char的指針。 所以你的代碼應該是這樣的:

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

int main(){
    int word;
    char cont;
    for (;;){
        int countword = 0;
        int countpunct = 0;
        printf("\nEnter the String: ");
        while ((word = getchar()) != EOF && word != '\n'){
            if (word == ' ' || word == '.' || word == '?' || word == '!' || word == '(' || word == ')' || word == '*' || word == '&'){
                countword++;
            }
            if (word == '.' || word == '?' || word == '!' || word == '(' || word == ')' || word == '*' || word == '&'){
                countpunct++;
            }
        }
        printf("\nThe number of words is %d.", countword);

        printf("\nThe number of punctuation marks is %d.", countpunct);

        printf("\nContinue? Y/N?");
        scanf("%c", &cont);
        if (cont!= 'y' && cont!= 'Y'){
            return 0;
        }
    }
}

還要注意countwordcountpunct被移動到外循環內。 這樣,對於每組新單詞,它們都會被初始化為 0。

暫無
暫無

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

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