The code has some problems. I’ll solve some, but it’s still not robust code because it doesn’t test other problems, I won’t go into those issues.
One problem is that to read text with white space you need to use fgets()
, and needs to treat the line change that must be switched to a terminator. Which leads to another problem: if you want 20 characters you need to reserve 21 bytes of buffer. And the scanf()
need to receive a pattern with the new line to leave no dirt on buffer.
At least this is a solution:
#include <stdio.h>
#include <string.h>
int main() {
int idade = 0;
printf("Hello! How old are you? ");
scanf("%d\n", &idade);
while (idade == 0) {
printf("\nAge cannot be 0 nor be decimal. Re-enter your age: ");
scanf("%d", &idade);
}
char nome[21];
fgets(nome, 20, stdin);
nome[strcspn(nome, "\n")] = 0;
printf("\nHello %s, aged %d!\n", nome, idade);
}
Behold working in the ideone. And in the replit. Also put on the Github for future reference.
It is possible to use a trick with the scanf()
, but understand that in real codes this function is rarely used for free data entry:
#include <stdio.h>
#include <string.h>
int main() {
int idade = 0;
printf("Hello! How old are you? ");
scanf("%d\n", &idade);
while (idade == 0) {
printf("\nAge cannot be 0 nor be decimal. Re-enter your age: ");
scanf("%d", &idade);
}
char nome[21];
scanf(" %[^\n]s", nome);
printf("\nHello %s, aged %d!\n", nome, idade);
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site (when you have enough score).
– Maniero