Always missing an value while printing outcomes (Problem 20 C)

Back to General discussions forum

wanghaoxing186     2024-03-04 14:16:01

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;
}
ecolog_veteran     2024-03-04 14:48:21
User avatar

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.

wanghaoxing186     2024-03-05 02:32:03

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.

Please login and solve 5 problems to be able to post at forum