【发布时间】:2014-01-19 15:24:17
【问题描述】:
你能帮我找出我在计算每行位数然后将其与总数进行比较时的错误吗?这是我计算每行位数的程序:
#include<stdio.h>
#include<string.h>
#include<ctype.h>
int main()
{
int pc, c, NumbersPerLine= 0, NumbersTotal=0, line= 1;
FILE *inputFile;
if(!(inputFile=fopen("C:\\Test\\Test.txt","r")))
{
printf("the file does not exist\n");
return 0;
}
for (pc='\n', c=fgetc(inputFile);c!=EOF;pc=c,c=fgetc(inputFile))
{
if (isdigit(c))
{
NumbersPerLine++;
}
else
if (c=='\n')
{
printf("%d %d\n", line++, NumbersPerLine);
NumbersPerLine= 0;
}
}
if (pc!='\n') printf("%d %d %d\n", line, NumbersPerLine);
fclose(inputFile);
}
但是现在我也必须添加文件中的总位数,我所做的只是逐行计算它们,然后将它们相加而不是全部计算。 我试图得到这样的结果:
1 (that's the number of the line) 5 (the number of digits per line) 18 (total digits)
2 5 18
3 4 18
4 1 18
5 1 18
6 1 18
7 1 18
我试着把 NumbersTotal++;在 NumbersPerLine++; 之后,但我得到的只是这个:
"1 5 5
2 5 10
3 4 14
4 1 15
5 1 16
6 1 17
7 1 18"
我也试过在'for'之前使用do-while
c=fgetc(inputFile);
do
{
NumbersTotal++;
}while(isdigit(c));
但在满足该条件后,程序结束并且不会继续使用“for”。你能帮帮我吗?
【问题讨论】:
-
"per line" -> 使用
fgets()而不是fgetc()。而且那个 for 循环太可怕了。 -
当出现“文件不存在”的错误消息时,没有什么比这更烦人的了。试试
char *path="C:..."; if(!(inputFile=fopen(path, "r"))) { perror(path);return EXIT_FAILURE;}