Home > Mobile >  Trying to make a program that fixes the code of another program
Trying to make a program that fixes the code of another program

Time:12-01

I am trying to make a program that can fix the code of another program.

This is the sample program I made that needs it's code fixed.

#include <stdio.h>
#include <math.h>

int
main (
) { printf("helloworld");
    return 0;
}

I started with this code

#include <stdio.h>

int main() {
    int chr ,areLibraries;
    areLibraries = 1;

    while ((chr = getchar()) != EOF) {
        if ((chr == '#') && (areLibraries == 1)) {
            while(chr != '\n') {
                putchar(chr);
                chr = getchar();
            }
            putchar(chr);
        } else {
            areLibraries = 0;

            if (chr == '\n') {
                continue;
            } else {
                putchar(chr);
            }
        }   
    }
}

Which is supposed to ignore #include .... in a c program and ignore any '\n' characters.

Before running the program ,I expected this to be the output.

#include <stdio.h>
#include <math.h>
intmain () { printf("helloworld");  return 0;}

But the program printed this instead

#include <stdio.h>
#include <math.h>
}

I've been trying for hours to find the issue ,but nothing seems to fix it.It's like the program thinks that every characters that is inputed after the #include statements end ,is a '\n' character.Does the issue have to do with my use of putchar() and getchar() ,or am I too dumb to find my mistake.

CodePudding user response:

Looks to me like the file you're trying to fix must have Windows line endings, that is \r\n. You're filtering out the newlines, but leaving the carriage returns. This will cause the last line to overwrite itself.

Try updating your program to this:

#include <stdio.h>

int main() {
    int chr ,areLibraries;
    areLibraries = 1;

    while ((chr = getchar()) != EOF) {
        if ((chr == '#') && (areLibraries == 1)) {
            while(chr != '\n') {
                putchar(chr);
                chr = getchar();
            }
            putchar(chr);
        } else {
            areLibraries = 0;

            if (chr == '\n' || chr == '\r') { // <- CHANGE HERE
                continue;
            } else {
                putchar(chr);
            }
        }   
    }
}
  •  Tags:  
  • c
  • Related