fgetc不工作C-重复返回相同的字符 [英] fgetc not working C- returns same char repeatedly

查看:153
本文介绍了fgetc不工作C-重复返回相同的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C中工作,并尝试读取一个文件,并将数组中保存fgetc返回的字符。问题是fgetc反复返回一个随机字符。在评论中标记了位置。例如,wwwwwwwwww ...或@@@@@@@@@@@ ...。任何帮助是赞赏。这是函数:

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


推荐答案

打印字符

printf("%c", &ch);

这实际上是试图在栈上打印你的ch的地址(解释为char)。

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

您想要的是:

printf("%c", ch);

这将正确打印堆栈地址的内容(作为char)

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

这篇关于fgetc不工作C-重复返回相同的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆