简体   繁体   English

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

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

Ok i modified my code but cannot get it to break when the user inputs 0. I tried 0, '0', and "0" and neither break the 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);

}

Your inner loops break when word is either EOF or \\n .wordEOF\\n时,您的内部循环会中断。 Since you never modify it when you get to the end of the outer loop, the condition will always be true.由于到达外循环结束时您永远不会修改它,因此条件将始终为真。

Going back to your pre-edit code, all you really need is to change scanf("%c", word);回到你的预编辑代码,你真正需要的是改变scanf("%c", word); to scanf("%c", &word);scanf("%c", &word); , although you should use a separate char variable for that, since the %c format specifier expected a pointer to char . ,尽管您应该为此使用单独的char变量,因为%c格式说明符需要一个指向char的指针。 So your code should look like this:所以你的代码应该是这样的:

#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;
        }
    }
}

Note also that countword and countpunct are moved inside of the outer loop.还要注意countwordcountpunct被移动到外循环内。 That way, they're initialized to 0 for each new set of words.这样,对于每组新单词,它们都会被初始化为 0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM