1
This is the excerpt of my code with the problem:
int main (void) {
int n_sentencas, n_perguntas;
scanf("%d %d", &n_sentencas, &n_perguntas);
fflush(stdin);
char** sentenca; // ponteiro para matriz que armazena as sentencas
sentenca = malloc(n_sentencas * sizeof(char*)); // alocacao das linhas da matriz que vao representar uma sentenca cada
char** pergunta; // ponteiro para matriz que armazena as perguntas
pergunta = malloc(n_perguntas * sizeof(char*)); // alocacao das linhas da matriz que vao representar uma pergunta cada
for (int i = 0; i <= n_sentencas; i++) { // for que le as sentencas
sentenca[i] = malloc(400 * sizeof(char));
fgets(sentenca[i], 400, stdin);
}
for (int i = 0; i < n_perguntas; i++) { // for que le as perguntas
pergunta[i] = malloc(400 * sizeof(char));
fgets(pergunta[i], 400, stdin);
}
for (int i = 0; i < n_sentencas; i++) { // for que imprime as sentencas
printf("sentenca %d: \n", i+1);
printf("%s\n", sentenca[i]);
}
for (int i = 0; i < n_perguntas; i++) { // for que imprime as perguntas
printf("pergunta %d: \n", i+1);
printf("%s\n", pergunta[i]);
}
The problem that occurs is that the first row of the matrix sentenca
is always ignored, as in the example below:
Entree:
3 2
bom
dia
amigos
como vao voces?
(nessa linha deveria ter uma quinta entrada, mas o programa imprime os valores apenas
com 4 strings na entrada, ao invés de 5)
Then the exit is as follows:
sentenca 1:
sentenca 2:
bom
sentenca 3:
dia
pergunta 1:
amigos
pergunta 2:
como vao voces?
I’d like to know how to fix it.
The problem and solution is the same as I speak in this question. In your case the solution is to consume the
\n
withfgetc(stdin)
after the firstscanf
. Althoughfflush(stdin);
try to do the same, this will only work in some implementations, and typically in linux does not work.– Isac
@Isac I tried to use
fflush
to solve this problem and it didn’t work, so I ended up having to ask here, since I didn’t know thefgetc
. Incidentally, that\n
that’s the one?– sabonet
It is the enter that you put to enter the values, and that the
scanf
did not consume and ends up being the only thing that the firstfgets
reads– Isac