Why does this loop in C not work?

Go To StackoverFlow.com

1

I'm trying to make a loop so that a user can enter a number, and after each number they are prompted if they want to enter another number or not. If they choose anything but n or N, then count is increased, so the loop keeps going, but instead it doesn't!

#include <stdio.h>

main() {

    int nums[10], i, tot = 0;
    int answer;
    double avg;

    int count = 1;

    for (i = 0; i < count; i++) {
        printf("Enter number %d: ", i + 1);
        scanf("%d", &nums[i]);
        printf("Enter another number? ");
        scanf(" %c", &answer);
        tot += nums[i];
        if (answer != 78 && answer != 110) {
            count++;
        }
        else { count = count - 1; }
        printf("[c:%d][i:%d]", count, i);
    }

}

The output I get:

Enter number 1: 2
Enter another number? y
[c:2][i:0]Enter number 2: 3
Enter another number? y
[c:3][i:1]Enter number 3: 4
Enter another number? n
[c:4][i:2]Enter number 4: 1
Enter another number? n
[c:5][i:3]Enter number 5: 2
Enter another number? n
[c:6][i:4]Enter number 6: 2
Enter another number? n
[c:7][i:5]Enter number 7: ^C

the count variable does not decrement when I enter n or N, why not? It's supposed to decrement to exit out of the loop, and using break; doesn't work either!

2012-04-04 21:46
by eveo
In your [c:][i:] debugging, you should add [answer:]. If you look at the loop, the only thing that would make sense is that answer is not what you think it is. You should also check the return value of scanf - Corbin 2012-04-04 21:49
Print out answer to check what you actually get - Daniel Fischer 2012-04-04 21:50
Use a do while loop, with a char 'answer' variable to detect if the loop should end or no - Greg Brown 2012-04-04 21:50
Removing the space before %c will not allow me to enter input since it takes in \n - eveo 2012-04-04 21:52
Big-endian machine - Daniel Fischer 2012-04-04 21:53
@DanielFischer yup - eveo 2012-04-04 21:55
Just for the record, it works on my (little-endian) box, so it's the endianness indeed (almost certainly) - Daniel Fischer 2012-04-04 21:56
Nah, it was just that I should have defined int answer as char answer lol - eveo 2012-04-04 22:00
It was the endianness causing that. The char was being stored on the wrong part of the int. But yes, making it a char does fix that - Corbin 2012-04-04 22:15
Ah yeah true, thanks - eveo 2012-04-04 22:52


7

you probably want to make answer of type char instead of int.

2012-04-04 21:49
by keety
Wow, I always fall into dumb traps like this. Thank you - eveo 2012-04-04 21:54
Ads