![](/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.