我制作了一个简单的文件读取程序,它在DEV C gcc编译器中成功运行,但它显示错误Debug Assertion Failed
。
我搜索了12天前有人问了同样的问题,
答案显示他的错误是在声明中
if (file = fopen (name, "w+") == NULL) {
...
}
并将两个陈述分开为
file = fopen(name, "w+");
if (fp == NULL) { ...}
我的代码
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main()
{
int nos = 0, noc = 0, nol = 0;
char ch;
FILE *fp;
fp = fopen("Sarju.txt", "r");
while (1)
{
ch = fgetc(fp);
if (ch == NULL)
{
printf("The file didn't opened\n");
break;
}
if (ch == EOF)
break;
noc++;
if (ch == ' ')
nos++;
if (ch == '\n')
nol++;
}
if (ch != NULL)
fclose(fp);
printf("Number of Space : %d\nNumber of Characters : %d\nNumber of lines : %d\n", nos, noc, nol);
_getch();
return 0;
} `
我的错误
Debug Assertion失败了!程序:... o 2015 \ Projects \ Let Us C Solutions \ Debug \ Let Us C Solutions.exe文件:minkernel \ crts \ src \ appcrt \ stdio \ fgetc.cpp行:43表达式:stream.valid()有关信息关于程序如何导致断言失败,请参阅有关断言的Visual C ++文档。 (按“重试”调试应用程序)
答案 0 :(得分:0)
您的代码有几个问题。更正后的代码为:
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
int main()
{
int nos = 0, noc = 0, nol = 0;
int ch; /* `int`, not `char` */
FILE *fp;
fp = fopen("Sarju.txt", "r");
while (1)
{
/*ch = fgetc(fp); After the below `if`, not here */
if (fp == NULL) /* `fp`, not `ch` */
{
printf("The file didn't opened\n");
break;
}
ch = fgetc(fp);
if (ch == EOF)
break;
noc++;
if (ch == ' ')
nos++;
if (ch == '\n')
nol++;
}
if (fp != NULL) /* `fp`, not `ch` */
fclose(fp);
printf("Number of Space : %d\nNumber of Characters : %d\nNumber of lines : %d\n", nos, noc, nol);
_getch();
return 0;
}
int
,fgetc
返回int
,而非char
。fp
是否不是NULL
,而不是ch
。ch = fgetc(fp);
在错误的地方。