0

So this seems like a relatively simple C problem in theory, but in practice it's a little difficult. So a user inputs a number N, after which they input N characters. A program is supposed to count the number of occurrences of uppercase letters (or lowercase or whatever, that's not the issue here). This is what the console should look like (for instance, the user enters the number 3):

Enter N: 3

Enter character 1: p

Enter character 2: /

Enter character 3: s

And so on. The way I tried doing this is:

#include <stdio.h>
#include <ctype.h>
int main(int argc, char **argv)
{

    int n;
    scanf("%d", &n);
    int b = 0;
    for (int i = 1; i<=n; i++){
        printf("Enter character %d: ", i);
        char c;
        scanf("%c", &c);
        if (islower(c)) b++;
    }
    printf("%d\n", b);

    return 0;
}

This seems like a good solution but the problem is that apparently the ENTER key pressed after inputting N, or after inputting any of the characters is recognized as one of the characters that needs to be inputted. Now I'm not sure if this is the way it's supposed to work, but isn't the ENTER key's role to tell the console when the user finished a certain input? I mean if I can't press enter upon inputting N without it being caught as a character, how am I supposed to even input N? This is what the console looks like when I test this:

the test

So I guess I could somehow make the loop run twice the time of N and each time ignore the first character for instance, but I'm wondering if I should be looking at this as a coding problem or as a console problem.

Any ideas? Thanks.

Koy
  • 486
  • 5
  • 16
  • 1
    `scanf` leaves a newline in the input buffer. Most format specifiers will filter out leading whitespace, but `%c` is one that does not, unless you include a space before the specifier, as in `scanf(" %c", &c);` – Weather Vane Nov 24 '17 at 10:40
  • Works well, thanks. – Koy Nov 24 '17 at 10:56

0 Answers0