I need help with a really really simple code ...

Im a little "noob" in c ... But a rather simple code is breaking my mind...

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>



main()

{
int i;
char word[100];
char trocas[100];
FILE *fpin;
FILE *fpout;

fpin = fopen ("frases.txt", "r");
fpout = fopen("mistura.txt", "w");


if (fpin == NULL)
{
printf("Erro ao abrir o ficheiro.");
exit(1);
}


if(fpout == NULL)
{
printf("Erro ao abrir o ficheiro.");
exit(1);
}

//And i dont think fgetc should be the best option but i have very limited Knowledge in c
for(i=0;i<100;i++)
{
word[i]=fgetc(fpin);
}



//Im trying to save one array to another but also changing is index so when it appears in the final file its a little scrambled ...
for(i=0;i<100;i++)
{
trocas[i]=word[i+1];
trocas[i+1]=word[i];
}


fputs(trocas,fpout);

printf("OK\n");
fclose(fpin);
fclose(fpout);
system("PAUSE");
}



The purpose of this program is to read a txt file sending it to an array , then it sends to another but a little scrambled and then it sends to the final file ... name fpout ...
1
2
3
4
5
for(i=0;i<100;i++) 
{
  trocas[i]=word[i+1];
  trocas[i+1]=word[i];
}


i think the probem is i+1 your loop runs to 99 because you array has elements from 0-99 that is ok. But the last element you read is 99+1=100, but this element does not exist.

And what are you trying to do exactly?

You are doing this:

1
2
3
4
5
6
7
8
9
10
trocas[0] = word[1];
trocas[1] = word[0];

Trocas[1] = word[2];
Trocas[2] = word[1];

Trocas[2] = word[3];
Trocas[3] = word[2];

etc...


as you can see you are writing double values. elements in Trocas are being overwritten. I guess that is not what you want?
Last edited on
Change the loop incrementer to "i += 2". It will not override (because 'i+1' is skipped) and it will only go to 98 causing no out-of-bounds access.
im trying to put trocas[1] being word[2] and so on ... your write a sentence in a file like

"hello world"

im trying to put it into an array and trade it to another so it will end like this(example)

"llowe olrdw"


just and example
the problem is when i execute the file ... The elements of the array "Trocas" should be the ones in array word but a little scrambled ... But its the same ... Not scrambled ... Both arrays are identical but i thought that for would scramble theirs index ...
Topic archived. No new replies allowed.