1

In this code it need to calculate the number of times the operators appear. It doesn't calculate it and while running the code it prints "Please enter a note. to finish press Q:" twice and i don't know whats wrong.

#include <stdio.h>

int main(void)
{

    char note;
    int result1 = 0, result2 = 0, result3 = 0, result4 = 0;


    do
    {
        printf("Please enter a note. to finish press Q:\n");
        scanf("%c", &note);
        switch (note)
        {
        case'+':
            result1 = result1 + 1;
            break;
        case'-':
            result2 = result2 + 1;
            break;
        case'*':
            result3 = result3 + 1;
            break;
        case'/':
            result4 = result4 + 1;
            break;
        }

    } while (note != 'Q');

    printf("+ appears %d times\n", result1);
    printf("- appears %d times\n", result2);
    printf("* appears %d times\n", result3);
    printf("/ appears %d times\n", result4);

    system("pause");
}
dustinos3
  • 934
  • 3
  • 17
  • 27
  • Next time you copy & paste the code from your IDE to your question exactly how it is. – Swordfish Nov 20 '18 at 18:16
  • Not identical question - but worth reading: https://stackoverflow.com/questions/13542055/how-to-do-scanf-for-single-char-in-c – Igal S. Nov 20 '18 at 18:21
  • You are reading the character (ex. `+`) and then reading a newline (you pressed enter). You can not print the `Plese enter a note ..` if the last character is newline or if you receive a newline scanf again or similar. – KamilCuk Nov 20 '18 at 18:24
  • Try using `getchar()` instead of `scanf()` – iVoid Nov 20 '18 at 19:14
  • Tip: **always** add a `default` case to a `switch` statement. This helps you detect unexpected events. – Tim Randall Nov 20 '18 at 20:01

2 Answers2

0

To debug this, insert

  printf("note='%c'\n", note);

immediately after the scanf. You'll see the problem immediately.

Alcamtar
  • 1,478
  • 13
  • 19
0

Using scanf("%c", %c), you will be reading one character at a time. Which is fine, but..

scanf will not "re-scan" for input, until the buffer is clear.

So, if the user were to input something longer than 1 character, your loop will iterate for every character the string is long + 1 (\n counts as a character).

Example (note it loops 3 times +, +, \n):

Please enter a note. to finish press Q:
++
Please enter a note. to finish press Q:
Please enter a note. to finish press Q:
Please enter a note. to finish press Q:

That's the trick. You need to change your code to accommodate this (i.e. hide the please enter message until empty or read a char array note[128]... scanf('%s', note) vs. single character with a sub loop to iterate the over the input, etc. or some other way).

static_cast
  • 1,174
  • 1
  • 15
  • 21