gpt4 book ai didi

c - Visual Studio 2015 显示调试断言失败

转载 作者:行者123 更新时间:2023-11-30 17:06:18 25 4
gpt4 key购买 nike

我制作了一个简单的文件读取程序,可以在 DEV C gcc 编译器中成功运行,但显示错误调试断言失败。我搜了一下,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 failed! Program: ...o 2015\Projects\Let Us C Solutions\Debug\Let Us C Solutions.exe File: minkernel\crts\src\appcrt\stdio\fgetc.cpp Line: 43 Expression: stream.valid() For information on how your program can cause an assertion failure, see the Visual C++ documentation on asserts. (Press Retry to debug the application)

最佳答案

您的代码有几个问题。更正后的代码为:

#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;
}
  1. 我使用了 int,因为 fgetc 返回的是 int,而不是 char
  2. 您应该检查 fp 是否不是 NULL,而不是 ch
  3. ch = fgetc(fp); 位置错误。

关于c - Visual Studio 2015 显示调试断言失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34824568/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com