-2

I want to have 3 inputs of symbols e.g. | or %, but instead of getting | | %, I got | |.

Terminal:

| ^ !

 | ^

The code is here:

#include <stdio.h>

char a[10], b[10], c[10];
int i;
int count;

int main(int argc, char const *argv[]) {
    scanf("%d", &count);

    for (i = 0; i < count; i++) {
        scanf("%c %c %c", &a[i], &b[i], &c[i]);
        printf("%c %c %c\n", a[i], b[i], c[i]);
    }
    return 0;
}

Please tell me what am I doing wrong. Thanks.

chqrlie
  • 131,814
  • 10
  • 121
  • 189
user3798451
  • 51
  • 1
  • 1
  • 6

1 Answers1

0

To read single characters symbols optionally separated by whitespaces, you must explicitly ignore this whitespace with a in the format string before the %c.

Also check the return value of scanf().

Here is a corrected version:

#include <stdio.h>

int main(int argc, char const *argv[]) {
    char a[10], b[10], c[10];
    int i, count;

    if (scanf("%d", &count) == 1 && count <= 10) {
        for (i = 0; i < count; i++) {
            if (scanf(" %c %c %c", &a[i], &b[i], &c[i]) != 3)
                break;
            printf("%c %c %c\n", a[i], b[i], c[i]);
        }
    }
    return 0;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189