如何在C中多次运行循环?

时间:2015-09-14 20:56:38

标签: c loops for-loop

好的我修改了我的代码,但是当用户输入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);

}

1 个答案:

答案 0 :(得分:0)

wordEOF\n时,您的内部循环会中断。由于在到达外循环结束时从不修改它,因此条件始终为真。

回到编辑前的代码,您真正需要的是将scanf("%c", word);更改为scanf("%c", &word);,尽管您应该使用单独的char变量,因为{{ 1}}格式说明符期望指向%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; } } } countword移动到外部循环内部。这样,对于每组新单词,它们都被初始化为0.