问题添加从fgetc收到的值?

时间:2015-12-04 01:55:57

标签: c

我编写了一个函数,用于从输入文件读取任何整数,找到这些数字的总和,并找到数字的总数(我工作了)。这是:

int total = 0;
int ncount = 0; 
int cse;
do
{
    cse = fgetc(infp);
    if(cse <= '9' && cse >= '0')
    {
        total += cse;
        ncount++;
    }
}while(cse != EOF);

fprintf(outp,"Number of numbers is %d\n", ncount);
fprintf(outp, "Total is %c\n", total);

如果我输入的78345应该等于总数= 27;我得到总数= 267.同样,如果我只打印fgetc值,我会得到像53 54 57等数字。但是,当我使用%c打印它时,我得到78345.如何使用此逻辑将这些值添加为总和?提前谢谢!

4 个答案:

答案 0 :(得分:3)

两件事。首先,您要添加字符ASCII值,而不是字符所代表的值:

fprintf(outp, "Total is %d\n", total);

您可能希望从中减去字符零的值,这只是一个简单的转换:

total += cse;

然后,第二,你打印一个字符值:

total += cse - '0';

使用整数格式化程序,如fprintf(outp, "Total is %c\n", total);

答案 1 :(得分:2)

UI返回单个字符代码,该代码不等同于字符数值。在您的代码中,您正在比较和添加字符代码值。

您需要将字符代码转换为整数,例如:

fgetc

答案 2 :(得分:2)

两个问题:

  • int num = cse - '0'; 应为total += cse;
  • total += ( cse - '0' );应为fprintf(outp, "Total is %c\n", total);

答案 3 :(得分:1)

您的阅读角色,并将其视为数字。

嗯,'0'是字符,其ascii值为48.

但你真正想要的是使用数字0。

正确的转换方式是

int total = 0; 
int cse; 

while( cse = fgetc( stdin ) && EOF != cse) 
{ 
    total += (cse - '0'); 
}