Raluca Damaris Lupeş
Raluca Damaris Lupeş

Reputation: 11

Writing in a file c

So basically in the program below I try to convert the upper case letter of a text into lower case letters and the lower case letters into upper case letter and print out the result in a file...but the only thing I get after running the program is a sequence of numbers... I tried to put as a second parameter to fprintf function "%s" but I didn't get a better result...

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

int main( )

{
    char c;

    int charToLowerCase = 0;
    int charToUpperCase = 0;
    int countCharacters = 0;
    FILE *in_file;
    FILE *out_file;
    in_file = fopen("input.txt", "r");
    out_file = fopen("output.txt", "w");
    c = fgetc(in_file);
    while (c != EOF)
    {
        if (c >= 'A' && c <= 'Z')
        {
            fprintf(out_file, "%d", tolower(c));
            charToLowerCase++;
        }
        else if (c >= 'a' && c <= 'z')
        {
            fprintf(out_file, "%d", toupper(c));
            charToUpperCase++;
        }
        else
            fprintf(out_file, "%d", c);

        c = fgetc(in_file);
        countCharacters++;
    }
    fclose(in_file);
    fclose(out_file);
    return 0;
}

Upvotes: 2

Views: 75

Answers (2)

Bathsheba
Bathsheba

Reputation: 234865

tolower and toupper return an int. (This is so they can handle EOF and other oddities).

You're almost safe to cast to char (strictly you ought to check the size of the returned int) and use an appropriate formatter which for a char, is %c.

Also, note that the C standard allows for encoding schemes where the lower and upper case letters are not necessarily in contiguous blocks. See EBCDIC. Strictly speaking if (c >= 'A' && c <= 'Z') is not a C-standards compliant way of testing if a letter is upper case.

Upvotes: 4

edtheprogrammerguy
edtheprogrammerguy

Reputation: 6049

Use %c in your fprintf statements. %d is for integers.

http://www.cplusplus.com/reference/cstdio/fprintf/

Upvotes: 3

Related Questions