【问题标题】:fgets adding string to another variablefgets 将字符串添加到另一个变量
【发布时间】:2015-01-19 13:39:41
【问题描述】:

我正在尝试用 C 语言做一个相对简单的库项目,但我被卡住了。我使用fscanf 设置一个变量(cote 是char[5]),然后fgets 设置另一个变量(titre 这是一个char[50])。这两个变量都属于一个名为Ouvrage 的结构。

问题是fgets 似乎将它正在读取的字符串添加到cote,在fgets 之前:strlen(o.cote) 返回 5,但之后它返回 31。

这是test.c 的代码:

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

typedef struct {
    char cote[5];
    char titre[50];
} Ouvrage;

void main(void)
{
    FILE *flot;
    Ouvrage o;

    // Opening the file

    flot = fopen("ouvrages.don", "r");

    if(flot == NULL)
    {
        printf("Error opening file.\n");
        exit(1);
    }

    // Reading the cote

    fscanf(flot, "%s%*c", o.cote);

    // Printing the length of cote

    printf("STRLEN: %d\t", strlen(o.cote));

    // Reading the titre

    fgets(o.titre, 50, flot);
    o.titre[strlen(o.titre) - 1] = '\0';

    // Printing the length of cote again.... Different.

    printf("STRLEN: %d\n", strlen(o.cote));
}

这是ouvrage.don 文件:

NJDUI
Charlie et la chocolaterie
ROM
Rhoal Doal

那么fgets 如何影响先前的变量以及如何阻止它?非常感谢任何帮助。

【问题讨论】:

    标签: c fgets scanf


    【解决方案1】:

    欢迎来到 c-strings 的世界。假设 cote 应该是 5 个字符长,您实际上需要保留 6 个字符以便为字符串结尾字符 ('\0') 留出空间;发生的事情是 fscanf 将该字符串字符写为 titre 的第一个字符,但随后 fgets 覆盖了它,这就是为什么你看到你所看到的。另请注意,就我而言, scanf 和相关是魔鬼的工具;为什么不只使用 fgets(它允许您指定要读取的最大字节数 [仔细阅读手册页以避免关闭一个])进行两次读取?

    【讨论】:

    • 感谢您的热烈欢迎和出色的回答。 C 中的字符串很有趣,不是吗 :) 感谢您的帮助!
    猜你喜欢
    • 2020-04-13
    • 1970-01-01
    • 1970-01-01
    • 2012-08-28
    • 2017-09-09
    • 1970-01-01
    • 1970-01-01
    • 2016-08-17
    • 1970-01-01
    相关资源
    最近更新 更多