yukimoda
yukimoda

Reputation: 183

C return if characters are the same

So, I'm just learning how to code in C and I'm a bit stumped by what my teacher is asking. Basically, we need to create a program that reads characters from two separate files character by character and if the two characters are the exact same it is to be printed to a third file. Normally, I would use an array to do this but, we have specifically been told that we are not allowed to use an array. I sort of have it working in that it prints characters to the third file but it prints numbers and punctuation in addition to characters. Obviously, I'm missing something but I don't know what it is. Here is my code:

int main(int argc, char *argv[]) {
    FILE *fp, *fp2, *ofp;
    char a, b;
    fp = fopen("input1a.txt", "r");
    fp2 = fopen("input1b.txt", "r");
    ofp = fopen("output.txt", "w");
        while((a=getc(fp))!= -1){ 
            b=getc(fp2);
            if(isalpha(a) == isalpha(b)){
               putc(a, ofp);
               letters++;
            }
        }
    return 0;
} 

From what I have read, isalpha should check to see if the character is an alphabetical character but, in this instance is there something better for me to use? Thanks for any help you can give me!

Upvotes: 0

Views: 120

Answers (1)

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53016

This is the problem

if(isalpha(a) == isalpha(b)) {

it sould be

if (isalpha(a) && isalpha(b) && a == b)

You are not comparing whether the characters are equal, but instead you are comparing if both are alphabetic or not, in case they are both alphabetic or they are both NOT alphabetic the character will be printed to the file.

Also, get used to writing safe code which is also clean and readable, like the following (note that there are elegant methods to handle errors, and you can add error messages):

int main(int argc, char *argv[]) 
{
    FILE *in[2];
    FILE *out;
    int chars[2]; // getc() returns `int' not `char'
    int counter;

    in[0] = fopen("input1a.txt", "r");
    if (in[0] == NULL)
        return -1;
    in[1] = fopen("input1b.txt", "r");
    if (in[1] == NULL) {
        fclose(in[0]);
        return -1;
    }

    output = fopen("output.txt", "w");
    if (output == NULL) {
        fclose(in[0]);
        fclose(in[1]);            
        return -1;
    }

    counter = 0;
    while (((chars[0] = getc(in[0])) != EOF) && ((chars[1] = getc(in[1])) != EOF) { 
        if (chars[0] == chars[1] && isalpha(chars[0])) {
           putc(chars[0], out);
           counter++;
        }
    }
    // Release ALL resources, it's a good habit
    fclose(inputs[0]);
    fclose(inputs[1]);
    fclose(output);
    // Not required but a good habit too
    return 0;
}

Don't use magic numbers, EOF is normally -1 but it's better to use EOF to make the code readable and robust.

Upvotes: 6

Related Questions