【问题标题】:Debug Assertion Failed, Expression stream != nullptr调试断言失败,表达式流!= nullptr
【发布时间】:2016-08-05 02:03:15
【问题描述】:

使用Visual Studio IDE,用C编写。程序是读取一个基本的.txt文件,将华氏温度转换为摄氏温度,然后写入新的.txt文件 为什么找不到.txt文件?这是我的代码:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main(void)
{
double tempArray[30];
double temp;
double sum = 0;
int input_status;
int count = 0;
double convert;
FILE *infile, *outfile;
infile = fopen("temperature.txt", "r");
if (infile == NULL) {
    perror("Failed: ");
    return 1;
}
outfile = fopen("results.txt", "w");

int i = 0;
input_status = fscanf(infile, "%lf", &temp);
double max, min = temp;
while (input_status != EOF)
{

    tempArray[i] = (temp - 32) * 5 / 9; ;
    sum += tempArray[i];

    fprintf(outfile, "%f \n", tempArray[i]);

    if (tempArray[i] > max)
        max = tempArray[i];

    if (tempArray[i] < min)
        min = tempArray[i];

    count++;
    i++;

    input_status = fscanf(infile, "%lf", &temp);

}

double average = sum / count;

fprintf(outfile, "\n The average of the temperatures is %f \n", average);
fprintf(outfile, "\n The maximum of the temperatures is %f \n", max);
fprintf(outfile, "\n The minimum of the temperatures is %f \n", min);

fclose(infile);
fclose(outfile);
system("pause");

}

here's where the .txt file is

this is the error code i received

【问题讨论】:

  • 您没有检查fopen 是否成功。结果的fopen 似乎失败了。
  • 请不要将短信作为图片发布。将其作为文本粘贴到问题中,以便其他人可以更轻松地复制它以在 cmets/answers 中引用。
  • 即使我检查它是否成功打开,也不会改变它不成功的原因。为什么找不到 .txt 文件?
  • 您传递给fopen 的文件名是相对于当前工作目录的。调试时,有一个项目设置允许您将当前工作目录 指向您喜欢的任何目录。您还可以在程序中更改当前工作目录(在类unix 系统上使用chdir)。如果您要打开的文件不在当前工作目录中,那么您需要指定文件的完整路径,例如fopen("c:\\projects\\TempRecorder\\temperature.txt","r");.

标签: c visual-studio compiler-errors


【解决方案1】:

我将文件命名为“temperature.txt”并且已经是一个.txt文件,所以文件名实际上是“temperature.txt.txt”。小错误,大问题。谢谢你们的帮助。

【讨论】:

    【解决方案2】:

    运行的可执行文件位于 Debug 文件夹中(在本例中),因此 temperature.txt 需要位于该文件夹中,或者需要将 "..\temperature.txt" 或类似的传递到 fopen()

    【讨论】:

    • 我没有看到 kaylum 看到了什么,所以我无能为力。但作为另一个观察,您在Projects\TempRecorder.c\TempRecorder.c\ 中显示temperature.txt,但在Projects\TempRecorder.c\Debug\ 中显示可执行文件,因此在这种情况下fopen() 的相对路径实际上是..\TempRecorder.c\temperature.txt
    • 所以我必须把整个路径从我的 C 盘开始或放入调试正确?因为我都尝试了,但仍然无法运行
    猜你喜欢
    • 2018-03-23
    • 1970-01-01
    • 1970-01-01
    • 2013-06-06
    • 2020-06-24
    • 1970-01-01
    • 2020-02-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多