gpt4 book ai didi

c - 从文件中读取并存储在 C 中

转载 作者:太空宇宙 更新时间:2023-11-04 08:50:09 25 4
gpt4 key购买 nike

我正在尝试读入一个字符串后跟数字的文本文件,然后存储它的内容。到目前为止,如果格式正确,我只能让它打印出字符串(或只是 int,或两者)。如何跳过空白行或格式错误的行(当前重复前一行)并存储结果?

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

#define MAX_LINE_LENGTH 400

int main ()
{
char input[MAX_LINE_LENGTH];
char name[MAX_LINE_LENGTH];
int number;

FILE *fr;
fr = fopen ("updates.txt", "r");
if (!fr)
return 1;
while (fgets(input,MAX_LINE_LENGTH, fr)!=NULL)
{
/* get a line, up to 200 chars from fr. done if NULL */
sscanf (input, "%s", name);
/* convert the string to just a string */
printf ("%s\n", name);
}
fclose(fr);
return 0;
}

示例文本文件

Cold 510 FlamesDoggy                      4Flames 11Cold 6

最佳答案

您可以使用 fscanf 函数。格式字符串中的空格使其忽略任何空格、制表符或换行符。

关于c - 从文件中读取并存储在 C 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19969378/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com