【问题标题】:program works but when I debug it says "<error reading characters in string.>" in line when reading file line by line程序可以工作,但是当我调试它时,它在逐行读取文件时显示“<error reading characters in string.>”
【发布时间】:2021-04-07 22:53:48
【问题描述】:

我写了这段代码:

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

int main(int argc, char *argv[])
{
    FILE *actionfpnt;
    char* line[70];
    actionfpnt = fopen(argv[1], "r");
    if (actionfpnt == NULL)
    {
        printf("Error: opening %s failed\n", "actions");
    }
    else
    {
        while (fgets(line, 70, actionfpnt) != NULL)
        {
            printf("%s\n", line);
        }
        fclose(actionfpnt);
        return 0;
    }
}

而 argv[1] 是一个 txt 文件的地址,在这个文本文件中:

Initialize
Fatal_malfunction $$$ cpu Zi7 $$$ 130
Fatal_malfunction $$$ cpu Zi5 $$$ 15
Returned_from_customer $$$ cpu Zi7 $$$ 10
Rename $$$ bloblo12zZzZ $$$ Zbloblo
Returned_from_customer $$$ Zblabla $$$ 10
Finalize

令人困惑的部分是代码实际上可以工作,但是当我尝试调试它时,我在变量“line”中看到:"&lt;error reading characters in string.&gt;"。 输出是:

Initialize

Fatal_malfunction $$$ cpu Zi7 $$$ 130

Fatal_malfunction $$$ cpu Zi5 $$$ 15

Returned_from_customer $$$ cpu Zi7 $$$ 10

Rename $$$ bloblo12zZzZ $$$ Zbloblo

Returned_from_customer $$$ Zblabla $$$ 10

Finalize

当我尝试使用 line 执行任何其他操作时,我不能,因为“line”实际上不包含任何内容。 我真的很感激有一种方法可以解决这个问题,并解释为什么代码可以工作并且即使存在这个问题也能得到正确的输出。

【问题讨论】:

    标签: c string pointers file-io


    【解决方案1】:

    你想要char line[70];而不是char* line[70];

    char* line[70]; 是一个包含 70 个指向 char 的指针的数组。


    由于fgets() 包括读取您想要printf 的行尾,而无需额外终止\n

      printf("%s", line);
    

    虽然不需要格式化,但使用 fputs() 就足够了:

      fputs(line, stdout);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-02
      • 2021-10-25
      • 1970-01-01
      相关资源
      最近更新 更多