-1
I’m trying to solve a problem with the URI Online Judge platform: Problem 1024 and I am receiving Wrong Answer 5% (I asked here, because in the URI forum itself I did not get answers). Basically I have to store as many phrases as the user wants. Scroll through each of the sentence characters and perform operations that encrypt the text (For example, in the first step through the sentence, it is necessary to scroll the characters 3 positions to the right - the letter 'a' becomes’d' -, in the second pass the text should be reversed and in the third the characters from the half of the string should be moved one position to the left.
I decided to make an array of strings to store each sentence. But an error occurs in reading: The program simply skips the first input line. So, if someone type '4', indicating that it will enter with 4 lines of text, the first line is skipped and the program stores only 3 sentences.
Does anyone know what could be causing this?
Code:
#include <stdio.h>
#include <string.h>
int main(void){
int n, i, j, k, cont;
scanf("%d", &n);
char linhas[n][1001], aux[10001];
for(i = 0; i < n; i++){
fgets(linhas[i], 1000, stdin);
//Deslocando três posições para a direita
for(k = 0; k < strlen(linhas[i]); k++){
if((linhas[i][k] >= 65 && linhas[i][k] <= 90) || (linhas[i][k] >= 97 && linhas[i][k] <= 122))
linhas[i][k] = linhas[i][k] + 3;
}
//Criando uma cópia auxiliar da string
strcpy(aux, linhas[i]);
cont = strlen(linhas[i]) - 1;
for(k = 0; k < strlen(linhas[i]); k++){
linhas[i][k] = aux[cont];
cont--;
}
//Deslocando uma posição para a esquerda
for(k = strlen(linhas[i]) / 2; k < strlen(linhas[i]); k++)
linhas[i][k] = linhas[i][k] - 1;
}
for(i = 0; i < n; i++)
printf("%s", linhas[i]);
return 0;
}
The first entry is an integer N indicating how many sentences will be read. Then insert the N phrases themselves.
– Daniel Cavalcante
I don’t know if it could be the cause of what you’re describing as "The program simply skips the first line of entry." but the fgets function places as an integral part of the read string the new line character (' n') that terminates the input. As you invert the string the first character becomes the ' n' and then when printing the string it will skip a line.
– anonimo
Got it! But I don’t think that’s because the program skips a line before I even insert some text. :/
– Daniel Cavalcante
The old problem of dirty buffer and mix scanf and fgets. After the scanf the ' n' continues in the input buffer and therefore the first fgets reads only this character. Consume this ' n' character with, for example:
scanf("%d ", &n);
(note the space at the end of the format).– anonimo