【问题标题】:How to run through a loop multiple times in C?如何在C中多次运行循环?
【发布时间】:2015-09-14 20:56:37
【问题描述】:

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

}

【问题讨论】:

  • scanf("%c", word); 将不起作用。替换为scanf("%c", &amp;word); 为什么你一次使用getchar 而另一次使用scanf
  • 奇怪的格式...继续在 if 行及其下方获取一个 K&R 样式的大括号,但 return 0 没有得到任何大括号。
  • 没有必要 continue 从无限循环的底部继续到下一次迭代,尽管它是无害的。这就是无论如何都会发生的事情。
  • 你应该看看do ... while 循环。 (注意:word 实际上是 char 并且应该这样声明(并且名称应该反映其含义;一个单词应该是一个字符串)。
  • do while 循环会替换整个 for(;;) 循环还是继续 for(;;) 循环?

标签: c loops for-loop


【解决方案1】:

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

回到您的预编辑代码,您真正需要的只是将scanf("%c", word); 更改为scanf("%c", &amp;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。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-30
    • 2013-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多