0

I am working in C and trying to read a file and save the chars returned by fgetc in an array. The problem is that fgetc is returning a random char repeatedly. Marked location in comment. For example, "wwwwwwwwwwww..." or "@@@@@@@@@@@@...". Any help is appreciated. Here is the function:

void removeCategories(FILE *category, int *prodPrinted){

    char more[16] = { '\0' }, hidden[17] = { '\0' }, temp = '\0', mdn[] = { "More Data Needed" }, hnl[] = { "Hidden non listed" };

    int newLineCount = 0, i, ch = '\0';

    do{
        /*shift char in each list -> one*/

        for (i = 16; i > 0; i--){
            if (i <= 16){
                hidden[i] = hidden[i - 1];
            }
            if (i <= 15){
                more[i] = more[i - 1];
            }
        }

        more[0] = hidden[0] = ch = ( fgetc(category));
        printf("%c", &ch);       /*problem is here, prints random char repeatedly*/

        if (strcmp(more, mdn) == 0 || strcmp(hidden, hnl) == 0){
            prodPrinted[newLineCount] = 0;
                printf("%c", more[0]);                             /*test print*/
        }
        if (ch == '\n'){
            newLineCount++;
        }
    } while (ch != EOF);
}
zwol
  • 135,547
  • 38
  • 252
  • 361
TinMan
  • 99
  • 2
  • 13

1 Answers1

1

Issue is in your call to print the character

printf("%c", &ch);

this is actually trying to print the address of your ch on the stack (interpreted as a char).

What you want is:

printf("%c", ch);

which will print the contents of that stack address correctly (as a char)

amdixon
  • 3,814
  • 8
  • 25
  • 34