[英]Infinite loop in C counting spaces
我正在編寫一個計算空格和元音的程序,但它不起作用,我想我做了一個無限循環。我將向您展示我的代碼:
int contar_p(char a[100]) {
int i = 0, spaces = 1;
while (a[i] != '\0' && i < 100) {
if (a[i] == ' ') {
spaces += 1;
i++;
}
}
return spaces;
}
int contar_v(char b[100]) {
int i = 0, counter = 0;
while (b[i] != '\0' && i < 100) {
if (b[i] == 'a' || b[i] == 'e' || b[i] == 'i' || b[i] == 'o' || b[i] == 'u') {
counter += 1;
}
i++;
}
return counter;
}
int main(void){
char phrase[100];
int words = 0, vowels = 0;
printf("write a phrase ");
gets(phrase);
palabras = contar_p(phrase);
vocales = contar_v(phrase);
printf("%d\n", words);
printf("%d", vowels);
return 0;
}
循環
while (a[i]!='\0'&&i<100){
if(a[i]==' '){
spaces+=1;
i++;
}
}
是一個無限循環。 將i++
放在if
之外。 將其更改為
while (a[i]!='\0'){ // No need of condition i < 100
if(a[i]==' '){
spaces+=1;
}
i++;
}
也許另一種方法可以幫助您更輕松地理解事物,我的意思是您確實知道還有 A,E,I,O,U,而不僅僅是 a,e,i,o,u。 你永遠不應該使用gets而是使用fgets,無論如何看看下面的程序:
#include <stdlib.h>
#include <stdio.h>
void countVowels(char* array){
int i,j,v;
i=0;
int count = 0;
char vowel[]={'a','e','i','o','u','A','E','I','O','U'};
while(array[i]!='\0'){
for(v=0;v<10;v++){
if (array[i]==vowel[v]){
j=i;
while(array[j]!='\0'){
array[j]=array[j+1];
j++;
}
count++;
i--;
break;
}
}
i++;
}
printf("Found %d Vowels\n",count);
}
void contar_p(char a[100]) {
int i = 0, spaces = 0;
for(i=0;a[i]!='\0';i++){
if(a[i]==' ')
spaces++;
}
printf("Found %d Spaces\n",spaces);
}
int main(void){
char a[]="aa bb EOU cc ii";
countVowels(a);
contar_p(a);
return 0;
}
輸出:
Found 7 Vowels Found 4 Spaces
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.