-1

i'm having a problem with this code. it should read from a file the letters and write them in one other file as in the following example

in.txt:

AAAAAAAAAABCCCCC
AAAAAAAAAAAAAAAAAAAA
BBCDERFG

out.txt

10A1B5C
20A
2B1C1D1E1R1F1G

but i continue to get this...

out.txt

10A1B5C
20A
2B1C1D1E1R1F1G 1A11.

can you tell me why i can't get where i want? thank you in advance

#include <stdio.h>
#include <stdlib.h>
#define MAX_STRING 514

int main(int argc, char *argv[])
{
    if(argc!=3) {
        fprintf(stderr, "Exactly 3 arguments required");
        exit(EXIT_FAILURE);
    }
    FILE *in;
    FILE *out;
    int i=0, k=0;
    char buffer[MAX_STRING];
    char string[MAX_STRING];
    in = fopen(argv[1], "r");
    if(in==NULL) {
        fprintf(stderr, "Couldn't open the file %s", argv[1]);
        exit(EXIT_FAILURE);
    }
    out=fopen(argv[2], "w");
    if(out==NULL) {
        fprintf(stderr, "Couldn't open the file %s", argv[2]);
        exit(EXIT_FAILURE);
        }
    while(fgets(buffer, MAX_STRING, in)!= NULL) {
        i=0;
        while(buffer[i]!='\n') {
            if(buffer[i]==buffer[i+1]) {
                k++;
                i++;
            }
            else {
                fprintf(out, "%c%d", buffer[i], k+1);
                i++;
                k=0;
            }
        }
        fprintf(out, "\n");
    }
    return 0;
}
Barmar
  • 741,623
  • 53
  • 500
  • 612

2 Answers2

0

You probably don't have a \n at the end of the file. So this loop:

while(buffer[i]!='\n')

won't stop and will consider all the buffer (including previous characters):

BBCDERFGAAAAAAAAAAAA
William
  • 2,695
  • 1
  • 21
  • 33
0

I suspect that there is no "\n" at the end of the last line - therefore buffer is still 'full' of the "A" from the previous line (i.e. there are 11 A's at the end of the buffer).

Check out this: Return value of fgets()

Rather than looking for "\n" to determine end of buffer, check for "\0" (which will be injected by fgets() at the end). i.e.

while(buffer[i]!='\0') 
{
  ...
}
Community
  • 1
  • 1
parade
  • 106
  • 3
  • it doesn't work yet. to make it work i have to add /n on in.txt file no matter i'm using while(buffer[i]!='\n') ot buffer[i]!='\0'. I understand what you want to say, but i still can't figure it out – Peter Fioretti Aug 08 '14 at 15:45