Back to General discussions forum
Hello, everyone!
I find if I use getchar()
to solve this problem, I'll always miss the last value while printing outcomes.
I've searched online and thought that would be the stdin
buffers remains aftering using scnaf()
. However, it just printed nothing when I tried the solutions I searched like fflush(stdin)
or while-statment.
Now I really don't know what's the problem here.
Here's my code:
#include <stdio.h>
int scan(char*);
int main(void) {
int num;
scanf("%d", &num);
int cnt[num]={0};
for (int i=0; i<num; ++i) {
char str[100];
int len=scan(str);
for (int j=0; j<len; ++j) {
if (*(str+j)=='a' || *(str+j)=='i' || *(str+j)=='u' || *(str+j)=='e' || *(str+j)=='o' || *(str+j)=='y') cnt[i]++;
}
}
for (int i=1; i<num; ++i) printf("%d ", cnt[i]);
return 0;
}
int scan(char* str) {
int len=0;
char c=getchar();
while (c != '\n') {
*(str+len) = c;
len++;
c=getchar();
}
return len;
}
You should also check the case when there's no input left while using getchar
.
I assume your program gets stuck in an infinite loop because of this.
Here is some similar question.
Thanks for your advising. It turns out it's my carelessness of not checking c!=EOF
in scan()
leads this circumstance. I really learned from this problem.