我试图读取一个字符串后跟一个数字的文本文件,然后存储它的内容。到目前为止,如果格式正确,我只能将其打印出来(仅打印字符串(或仅读取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;
}
示例文本文件
寒冷5 10火焰 狗狗4 火焰11 寒冷6
下面的代码为您的问题提供了可能的解决方案。
#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];
char namet[MAX_LINE_LENGTH];
int number;
FILE *fr;
fr = fopen ("updates.txt", "r");
if (!fr)
return 1;
while (fgets(input,MAX_LINE_LENGTH, fr)!=NULL)
{
memset(name, 0, MAX_LINE_LENGTH);
memset(namet, 0, MAX_LINE_LENGTH);
/* get a line, up to 200 chars from fr. done if NULL */
//sscanf (input, "%s %d", name, &number);
sscanf (input, "%s %s", name, namet);
// TODO: compare here for name shall only contain letters A-Z/a-z
// TODO: compare here for namet shall only contain digits
// If both above condition true then go ahead
number = atoi(namet);
if(name[0] != '\0')
{
/* convert the string to just a string */
printf ("%s %d\n", name, number);
//printf ("%s %s\n", name, namet);
}
}
fclose(fr);
return 0;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句