c - 为什么 fscanf 的读数为 0?

标签 c file io std scanf

我正在制作一个简单的程序,可以逐行读取文件。文件的每一行的格式为:整数、整数、字符。例如,文件如下:

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);
}

最佳答案

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

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

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

此外,从 scanf 的格式字符串中删除 '\n' 也是一个好主意,如下所示:

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

关于c - 为什么 fscanf 的读数为 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36324264/

相关文章:

c - 将两个数字数组相乘

c - 将 C 程序分成 void 函数

iphone - 在 objective-c 中使用 c 库

java - 获取文件夹中的文件数,省略子文件夹

java - Servlet 3.1 - 部件 - 方法 getParts() 未解决

c++ - 是否有一个 c++ 库可以从文件中读取命名列?

c++ - 文件IO从文件中读取多种类型

c - 将 c 控制台输入拆分为整数

python - 通过特定分隔符进行字符串操作并写入文本文件

c# - C# 中的 I/O 级联