1

The goal of the program is to scan a sequence of X, 1, 2 depending on how the user put them together and then show how many X he put in.

For some reason after the 8 X/1/2 I put (pressing ENTER 8 times since I put them one by one) It shows me the number 15 no matter how I put the numbers in.

My question why does it stop after 8 ENTERs when the for is set for i=1; i<=TOTOSIZE; i++ TOTOSIZE = 15

And why does it show the numebr 15 all the time instead of what its supposed to do.

#include <stdio.h>
#define TOTOSIZE 15

int main()
{
    int d = 0, i;
    char score;
    
    for (i = 1; i <= TOTOSIZE; i++)
    {
        scanf_s("%c", &score);
        if (score == 'X');
        {
            d++;
        }
        _flushall();
    }

    printf("%d", d);

    return 0;
}
adirk1
  • 219
  • 1
  • 11
  • 1
    Does this answer your question? [scanf("%c") call seems to be skipped](https://stackoverflow.com/questions/29775323/scanfc-call-seems-to-be-skipped) – yano Sep 21 '21 at 18:11
  • 1
    Does this answer your question? [scanf() leaves the new line char in the buffer](https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-the-buffer) – Adrian Mole Sep 21 '21 at 19:36

2 Answers2

1

I might've not understood you correctly, but to my understanding, you are inputting 15 different chars, each one being either 1, 2 or X, and counting how many X's were input. If this is correct, your problem seems to be a semicolon after the if statement. This code would work -

#include <stdio.h>
#define TOTOSIZE 15

int main()
{
    int d = 0, i;
    char score;
    
    for (i = 1; i <= TOTOSIZE; i++)
    {
        scanf_s("%c", &score);
        if (score == 'X')
        {
            d++;
        }
        _flushall();
    }

    printf("%d", d);

    return 0;
}
alonkh2
  • 533
  • 2
  • 11
1

There are two items in the following section of your code that may contribute to the skipping problem. (one also addressed by the other answer.)

for (i = 1; i <= TOTOSIZE; i++)
{
    //scanf_s("%c", &score);//using scanf to read char like this may skip due to newlines
    scanf_s(" %c", &score);//leading space in format specifier will consume space, including newline.
    //       ^ 
    if (score == 'X');
    {            //  ^ should not be there.  It nullifies the false result of test
        d++;
    }
    _flushall();
}

leading space reference

ryyker
  • 22,849
  • 3
  • 43
  • 87