好的,我修改了我的代码,但是当用户输入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。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句