Home > front end >  Scanning a char in for method doesn't work like expected
Scanning a char in for method doesn't work like expected

Time:09-22

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;
}

CodePudding user response:

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;
}

CodePudding user response:

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

  • Related