0
Hey there, guys! I’m just a beginner in the programming world and I’m facing the following problem: I would like to read the name of a player that must have at least 1 and at most 10 characters, at first I thought to create a larger character vector, such as 100, read and check, but still that wouldn’t guarantee that the user wouldn’t enter with a name greater than 100, would it? So I started to wonder if I could do that reading in some generic way. After researching and trying some things I got something close to what I wanted:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int tamanho;
char nome_do_jogador[13];
printf("Digite seu nickname:\n(Entre 1 e 10 caracteres!)\n");
//setbuf(stdin, NULL); NÃO FUNCIONOU, ENTÃO OPTEI POR fflush
fflush(stdin); //LIMPA O BUFFER DO TECLADO
fscanf(stdin, "%12[^\n]", nome_do_jogador); //LE 12 CARACTERES ATE ENCONTRAR UMA QUEBRA DE LINHA
tamanho=strlen(nome_do_jogador);
while(tamanho>10 || tamanho<1)
{
printf("Entrada invalida!\n");
printf("Digite seu nickname:\n(Entre 1 e 10 caracteres!)\n");
//setbuf(stdin, NULL);
fflush(stdin); //LIMPA O BUFFER DO TECLADO
fscanf(stdin, "%12[^\n]", nome_do_jogador);
tamanho=strlen(nome_do_jogador);
}
printf("O nickname e: %s", nome_do_jogador);
return 0;
}
I managed to work on Windows with GCC 7.3.0, but not on Linux also with GCC, but I can’t remember which version at the time.
Is there any way to do this in a generic way and that can maintain cross-platform?
Hugs!
I do not know if I understood the problem well, if you have read only 10 characters it will be respected (usually use the
fgets()
if it is something more complex, but a simple and space-free namescanf()
solves well).fflush(stdin)
It’s not drinkable and it’s documented that it doesn’t work for what people think it works, I don’t know why they use it. This code is very repetitive, you can do it in a much simpler way. And there are inefficiencies too, but if you do it right, it goes away by itself. I think you’re trying to fix a problem caused by another problem, fix the original problem.– Maniero
Running on Linux: https://ideone.com/B831RS
– Maniero
fflush(stdin)
represents undefined behavior in linux, and consequently does not clear the keyboard buffer. If you read with a large enough buffer (type 1024) the problem will solve itself.– Isac