I have a basic algorithm i want to try out, and to do so i have a txt
file with a number of inputs. To do so i redirect the stdin
to my input.txt
using the command, in the compiler: ./prog < input.txt
. Here's the mentioned code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void ExA(int n, int VALOR, int *sequencia){
int i,j,z,soma;
printf("%d - %d - %d\n",sequencia[0],sequencia[1],sequencia[2]);
for(i=1; i<=n; i++){
for(j=i; j<=n; j++){
soma = 0;
for(z=i; z<=j; z++){
soma = soma + sequencia[j];
}
if(soma == VALOR){
printf("SUBSEQUENCIA NA POSICAO %d\n", i);
return;
}
}
}
printf("SUBSEQUENCIA NAO ENCONTRADA\n");
}
int main(void){
int n, i, VALOR;
int *sequencia = malloc(sizeof(int));
char *buffer = malloc(sizeof(int) * 4);
while(read(0, buffer ,sizeof(buffer))){
sscanf(buffer,"%d %d",&n ,&VALOR);
if(n == 0 && VALOR == 0){
return 0;
}
else{
for(i = 0; i<n; i++){
read(0, buffer ,sizeof(buffer));
sscanf(buffer,"%d",&sequencia[i]);
}
}
ExA(n,VALOR,sequencia);
}
return 0;
}
The main function is responsible for reading from the input file and sending the values to the algorithm ExA
. In my input.txt
file i start with the following:
3 5
1
3
4
4 5
1
5
4
2
However when i print out my array (in the beginning of the ExA
function) where the numbers should be stored it prints out 1 - 4 - 5
instead of the wanted 1 - 3 - 4