我正在尝试读入一个字符串后跟数字的文本文件,然后存储它的内容。到目前为止,如果格式正确,我只能让它打印出字符串(或只是 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 5 10 Flames Doggy 4 Flames 11 Cold 6
最佳答案
您可以使用 fscanf 函数。格式字符串中的空格使其忽略任何空格、制表符或换行符。
关于c - 从文件中读取并存储在 C 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19969378/