-5
#include <stdio.h>

int main(void) {
        char UserInput;
        int num = 10;
        int counter = 0;

        while (num != counter) {
                printf("Enter the first letters ex A-Z:");
                scanf("%c", & UserInput);
                if (UserInput == 'A' || UserInput == 'a') {
                        printf("Uh-huh This is A. \n");
                } else if (UserInput == 'B' || UserInput == 'b') {
                        printf("Uh-huh This is B. \n");
                } else if (UserInput == 'Y' || UserInput == 'y') {
                        printf("Uh-huh this is Y. \n");
                } else if (UserInput == 'g' || UserInput == 'G') {
                        printf("yeah G. \n");
                } else {
                        printf(" unknown.\n");
                }
                counter++;

                printf("Number of input remaining: %d\n", 10 - counter);
        }

        return 0;
}

The purpose of the program is to loop 10 times and report the information each time. for example, if the user enters "A" or "a" it should print "A". ... But during the execution of the second loop, it takes the print statement as user input.

Here is the output.

  1. Enter the first letters ex A-Z:a //entered a
  2. Uh-huh This is A. //output
  3. Number of input remaining: 9 //output
  4. Enter the first letters ex A-Z: unknown. //why is it taking Unknown as input?
  5. Number of input remaining: 8
  6. Enter the first letters ex A-Z:
SecretAgentMan
  • 2,856
  • 7
  • 21
  • 41
validity
  • 1
  • 2
  • Description is a bit unclear. Please give the exact input, expected result and actual result. But one thing to be aware of `scanf("%c", & UserInput);` reads a single character and will not consume the newline/enter character that you are likely inputting. So the second loop will immediately read that newline character - that may be what you are describing. – kaylum Apr 03 '21 at 03:52
  • Please don't add info that is critical to the question in comments where it is easily missed and can't be formatted properly. [Edit](https://stackoverflow.com/posts/66927508/edit) the post to update it with that info. – kaylum Apr 03 '21 at 04:06

1 Answers1

2

Change the

scanf("%c", & UserInput);

to

scanf(" %c", & UserInput);

Space before %c removes any white space (blanks, tabs, or newlines). It means %c without space will read white sapce like new line(\n), spaces(' ') or tabs(\t). By adding space before %c, we are skipping this and reading only the char given.

Quoted from codesdope.com

PQCraft
  • 328
  • 1
  • 8