fgetc not working C- returns same char repeatedly

人盡茶涼 提交于 2020-01-06 23:09:46

问题


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);
}

回答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)



来源:https://stackoverflow.com/questions/20158061/fgetc-not-working-c-returns-same-char-repeatedly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!