![](/img/trans.png)
[英]In C - scanf() in a for loop is causing printf() to run multiple times
[英]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);
}
当word
是EOF
或\\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;
}
}
}
还要注意countword
和countpunct
被移动到外循环内。 这样,对于每组新单词,它们都会被初始化为 0。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.