【问题标题】:my code stopped reading in my .txt file我的代码停止在我的 .txt 文件中读取
【发布时间】:2013-12-08 16:44:36
【问题描述】:

我正试图让我的代码读入一个 txt 文件,它昨天还在工作,但现在当我通过“不调试启动”运行它时,它会打印出我提示它的消息,但就是这样,不管怎样我输入的内容会重新询问用户相同的问题,而不是打印 txt 文件中写入的内容。

#include <iostream>
#include <fstream>
#include <cmath>
#include <cstdlib>

void main ()
{
    FILE *file_in;
    char value;
    file_in = NULL;
    char unencrypted [1000];

    while (file_in == NULL)
    {
        printf("Please enter the name of the file you want to open:\n");
        scanf("%s", unencrypted);
        file_in = fopen(unencrypted, "r");
    }

    printf("\n This file consists of the following message: \n");
    while(!feof(file_in))
    {
        value = fgetc(file_in);
        printf("%c", value);
    }

    fclose(file_in);
}

【问题讨论】:

  • 你到底为什么同时使用&lt;fstream&gt;&lt;cstdlib&gt;?并在C++ 中使用 C 风格?
  • 您应该能够使用 errno 变量来获取更多信息。添加一行以在 fopen 返回 null 时打印 errno,这应该有助于您调试。
  • 阅读这个“while(!feof(file))”总是错误的” - stackoverflow.com/questions/5431941/…
  • 您应该通过将main 正确定义为int main 来向操作系统返回错误代码。

标签: c++ file input output


【解决方案1】:

如果它反复要求用户输入文件名,这意味着fopen 正在返回 NULL。你应该找出原因:

file_in = fopen(unencrypted, "r");
if (file_in == NULL)
    perror(unencrypted);

【讨论】:

    【解决方案2】:

    我不知道您在哪个平台上,但 IDE 通常会将发布版本和调试版本构建到不同的文件夹。如果您将测试文本文件放在调试文件夹中,然后进行发布构建,则该文件将无法通过相对路径访问。

    【讨论】:

      猜你喜欢
      • 2015-06-01
      • 2011-07-06
      • 1970-01-01
      • 1970-01-01
      • 2011-05-23
      • 1970-01-01
      • 2018-09-14
      • 1970-01-01
      • 2017-10-30
      相关资源
      最近更新 更多