Error while reading characters

Asked

Viewed 118 times

1

Instead of the code reading the three char variables, it reads 2 and prints the first.

#include <stdio.h>

int main() {
    char ch1, ch2, ch3;

    puts("Digite 3 caracteres, um apos o outro:");
    scanf("%c%c%c", &ch1, &ch2, &ch3);
    printf("%c\n%c\n%c", ch1, ch2, ch3);
    return 0;
}
  • 1

    I just tested your program and it’s working. It’s reading the 3 typed letters and showing on the screen.

  • I can confirm the @Electus comment. I ran the program and the output is what is expected.

  • This is very strange, because now it reads 2 characters and closes, I used this online compiler to test but still the program does not behave properly.

  • I added an answer. Take a look.

1 answer

3


What’s happening is this: You’re typing enter to each character typed. Do not enter, just type one character next to the other. And add a system("pause") so you can view the output:

#include <stdio.h>
#include <stdlib.h>

int main() {
    char ch1, ch2, ch3;

    puts("Digite 3 caracteres, um apos o outro:");
    scanf("%c%c%c", &ch1, &ch2, &ch3);
    printf("%c\n%c\n%c\n", ch1, ch2, ch3);
    system("pause");
    return 0;
}
  • Now it was, thanks! I’m only replacing the system("pause") with getchar() because I’m running on Gnu/Linux. Thank you!

  • I thought I had to enter, when I do it with integer numbers it works.

  • Keystroke enter he understands that it is also a character. Indeed it is, because enter is an escape character. So it gives the impression of reading only two characters, because the enter is "invisible".

  • I forgot all about it, thank you again.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.