Thus?
#include <stdio.h>
int main() {
char c;
printf("Digite um caractere:\n");
char c1 = getchar();
while ((c = getchar()) != '\n' && c != EOF) { }
printf("Digite um caractere:\n");
char c2 = getchar();
while ((c = getchar()) != '\n' && c != EOF) { }
printf("Digite um caractere:\n");
char c3 = getchar();
while ((c = getchar()) != '\n' && c != EOF) { }
printf("Primeiro caractere: %c\nSegundo caractere: %c\nTerceiro caractere: %c\n", c1, c2, c3);
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
Just failed to print the other two, it is not enough to have intention to show you have to pass the variable with the value for the print to be made.
I simplified a little too.
In fact the getchar()
does not work the way you expect it to. In fact every C data entry mechanism is confused by the way it manages the buffer. And there are many people who try magical solutions. Some work only in certain situations but as she sees it working she thinks it’s right. It’s full on the internet showing wrong. So it’s best to do the simple or make a function of yours that always works the way you expect.
I did a cleaning of buffer in the hand that always works, even if it is ugly.
Anyway, I don’t know if this is the purpose of the exercise. Is he saying that he needs to read the 3 characters separately? No, then you can do it another way. It is only specific in how it should print. So it works perfectly:
#include <stdio.h>
int main() {
printf("Digite três caracteres:\n");
char chars[4];
scanf("%3s", chars);
printf("Primeiro caractere: %c\nSegundo caractere: %c\nTerceiro caractere: %c\n", chars[0], chars[1], chars[2]);
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
You can read more on How to read from stdin in C?. And how to use the getchar()
in the right way (yes, it’s confusing).
but then I would be using an array, which would be "out of the rules", since the book had not taught yet, I understood its solution but it does not satisfy me. Thanks
– Henrique Hott
It’s not, I read in the question what’s written has nothing to say about it.
– Maniero