eveo
eveo

Reputation: 2843

Why does this C program completely skip my input?

CODE:

#include <stdio.h>
main() {

    int nums[100], i;
    char answer;
    int count = 0;
    double avg;

    for (i = 0; i < 100; i++) {
        printf("Enter number %d: ", i + 1);
        scanf("%d", &nums[i]);
        printf("Another? ");
        scanf("%c", &answer);
        count += nums[i];
    }
}

RUN:

~> a.out
Enter number 1: 1
Another? Enter number 2: 2
Another? Enter number 3: 3
Another? Enter number 4: 4
Another? Enter number 5: 5
Another? Enter number 6: 6
Another? Enter number 7: 7
Another? Enter number 8: 8
Another? Enter number 9:

It's supposed to ask me if I want to enter another number, but for some reason the scanf is not working. Also, I need to make it so that the user can enter 100 numbers, or any number under that, being prompted with a question of "do you want to enter another number". If the answer is no, it terminates, if it is yes, it carries on.

Upvotes: 1

Views: 5321

Answers (2)

DigitalRoss
DigitalRoss

Reputation: 146261

You need a space before the %c in order to skip the newline that wasn't read when scanf stopped at the end of the number.

I have some unsolicited advice...

  1. Don't use scanf(3) directly, it's too hard to make it do what you want. It's usually better to use fgets(3) and then sscanf(3).

  2. Compile with warnings turned on. (On my Mac that means cc -Wall ...)

And with warnings turned on, here your program with a few issues fixed:

#include <stdio.h>
int main(void) {

    int nums[100], i;
    char answer;
    int count = 0;
    // double avg;

    for (i = 0; i < 100; i++) {
        printf("Enter number %d: ", i + 1);
        scanf(" %d", &nums[i]);
        printf("Another? ");
        scanf(" %c", &answer);
        if (answer != 'y' && answer != 'Y')
          break;
        count += nums[i];
    }
    return 0;
}

Upvotes: 0

cnicutar
cnicutar

Reputation: 182774

Your first scanf leaves a newline in the buffer. It's because %d ignores trailing blanks while %c doesn't. Use this cheap trick to make the second scanf eat the blanks:

scanf(" %c", &answer);
       ^

The issue is common enough, you can read more about it in the C FAQ.

Upvotes: 6

Related Questions