【问题标题】:Why is fscanf reading 0?为什么 fscanf 读数为 0?
【发布时间】:2016-03-31 04:37:31
【问题描述】:

我正在制作一个可以逐行读取文件的简单程序。文件的每一行都采用以下格式:整数、整数、字符。例如,对于一个看起来像这样的文件:

1 2 A
2 3 B

程序的预期输出应该是:

1 2 A
2 3 B

但它正在打印

0 2 A
0 3 B 

我该如何解决?

#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#include <stdint.h>
#include <time.h>    

int main(int argc, char** argv) {

    char const* const fileName = argv[1];
    FILE* file = fopen(fileName, "r");

    char str[1];
    int key;
    int val;

    while (fscanf(file, "%d %d %s\n", &key, &val, str) != EOF) {

        printf("Read Integer %d \n", key );
        printf("Read Integer %d \n", val );
        printf("Read String %s \n", str );
    }


   fclose(file);

   return(0);
}

【问题讨论】:

  • 你读取了两个整数,所以需要"%d %d"...这样的格式
  • 您正在覆盖您的 str 数组。即使只输入一个字符,也会写入两个(字符,后跟一个空字节)。当然,如果输入了多个字符,那就更糟了。就目前而言,您会受到未定义行为的影响,因此所有赌注都已取消。

标签: c file io std scanf


【解决方案1】:

您将 str 声明为 char [1] 这是错误的。

您需要分配一个更大的str 来容纳'\0'。如下更改声明应该可以解决问题。

char str[2];  /* Or may be larger */
/*       ^    */

另外,最好将'\n'scanf 的格式字符串中删除为:

while (fscanf(file, "%d %d %s", &key, &val, str) == 3)
/*                           ^                   ^^^^  */

【讨论】:

  • @Pippi 不要在两者之间彻底改变问题,这会使现有答案无效。而是提出一个新问题。或者更好的是,始终校对您的问题并确保代码 sn-p 重现问题。
  • 对此感到抱歉。会的。
【解决方案2】:

您需要一个更大的字符串,您需要检查argc 的值,并且您需要一个更好的fscanf() 格式。也最好检查fscanf() 返回是 3。

#include <stdio.h>

#define N 500
#define XSTR(n) STR(n)
#define STR(n) #n

int main(int argc, char** argv)
{
    if (argc < 2)
    {
        fprintf(stderr, "I need one argument.\n");
        return 1;
    }

    char const* const fileName = argv[1];
    FILE* file = fopen(fileName, "r");

    char str[N + 1];
    int key;
    int val;

    // "%d %d %" XSTR(N) "s" expands as "%d %d %500s"
    while (fscanf(file, "%d %d %" XSTR(N) "s", &key, &val, str) == 3)
    {

        printf("Read Integer %d \n", key );
        printf("Read Integer %d \n", val );
        printf("Read String %s \n", str );
    }


   fclose(file);

   return(0);
}

编辑:我添加了宏,以便在更改 N 时更新格式。

【讨论】:

    猜你喜欢
    • 2021-01-11
    • 2022-01-01
    • 2016-03-02
    • 2013-05-04
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    相关资源
    最近更新 更多