如何在C中多次运行循环?
好的,我修改了代码,但当用户输入0时,无法使其中断。我尝试了0、'0'和'0',但都没有打破循环如何在C中多次运行循环?,c,loops,for-loop,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 && wo
#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);
}
#包括
#包括
int main(){
int字;
int countword=0;
int countpunct=0;
做{
printf(“\n输入字符串:”);
而((word=getchar())!=EOF&&word!='\n'){
如果(单词=“”| |单词=“”.| |单词=“”?“”| |单词=“”!“”| |单词=“”(‘| |单词=“”)‘| |单词=“”*‘| |单词=“”&’){
countword++;
}
如果(单词=='。|单词=='?'|单词=='!'|单词=='('|单词==')'|单词=='*'|单词=='&'){
countpunct++;
}
}
printf(“\n字数为%d.”,countword);
printf(“\n标点符号的数量为%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;
}
}
}
#包括
#包括
int main(){
int字;
字符控制;
对于(;;){
int countword=0;
int countpunct=0;
printf(“\n输入字符串:”);
而((word=getchar())!=EOF&&word!='\n'){
如果(单词=“”| |单词=“”.| |单词=“”?“”| |单词=“”!“”| |单词=“”(‘| |单词=“”)‘| |单词=“”*‘| |单词=“”&’){
countword++;
}
如果(单词=='。|单词=='?'|单词=='!'|单词=='('|单词==')'|单词=='*'|单词=='&'){
countpunct++;
}
}
printf(“\n字数为%d.”,countword);
printf(“\n标点符号的数量为%d.”,countpunct);
printf(“\N是否继续?”);
scanf(“%c”,续(&c));
if(cont!=“y”&&cont!=“y”){
返回0;
}
}
}
还要注意,countword
和countpunct
在外循环内部移动。这样,对于每一组新单词,它们都被初始化为0。scanf(“%c”,单词)代码>将不起作用。替换为scanf(“%c”和&word)为什么一次使用getchar
而另一次使用scanf
呢?奇怪的格式。。。继续在if行上获取一个K&R样式的大括号,并在其下获取一个,但返回0不会获取任何大括号。从无限循环的底部继续到下一次迭代不需要continue
,尽管这是无害的。不管怎样,这都会发生。你应该看看do。。。而
循环。(注意:word
实际上是一个char
,应该这样声明(名称应该反映其含义;单词应该是字符串)。do-while循环是替换整个for(;;)循环还是继续for(;;)循环?