我需要用fget分析前面的字符串阅读器,
然后我有一排:
name age steps\n
mario 10 1 2 3 4\n
joe 15 3 5\n
max 20 9 3 2 4 5\n每个列都有可变的步骤数,然后我可以用
sscanf(mystring, "%s %d", name, &age);在此之后,我有一个用于读取所有步骤的for循环。
int step[20];
int index=0;
while(sscanf(mystring,"%d", &step[index++])>0);但是,这个周期永远不会结束使用age列填充所有数组数据。
发布于 2016-06-08 10:52:14
这永远不会结束的原因是,您不断地提供相同的字符串来进行扫描。
sscanf提供了%n开关,它存储在a内到达之前读取的字符数量,这允许您在重新扫描之前根据输入字符串中的字符数量向前移动。
这会有用的:
int step[20];
int index=0;
int readLen;
while(sscanf(mystring,"%d%n", &step[index++], &readLen)>0) {
mystring += readLen;
}发布于 2016-06-08 10:49:19
在sokkyoku的回答中给出了一个可行的解决方案。
读取可变长度行的另一种可能是使用strtok,如下面的代码片段所示:
int getlines (FILE *fin)
{
int nlines = 0;
int count = 0;
char line[BUFFSIZE]={0};
char *p;
if(NULL == fgets(buff, BUFFSIZE, fin))
return -1;
while(fgets(line, BUFFSIZE, fin) != NULL) {
//Remove the '\n' or '\r' character
line[strcspn(line, "\r\n")] = 0;
count = 0;
printf("line[%d] = %s\n", nlines, line);
for(p = line; (p = strtok(p, " \t")) != NULL; p = NULL) {
printf("%s ", p);
++count;
}
printf("\n\n");
++nlines;
}
return nlines;
}上述函数的解释 getlines
文件fin中的每一行都使用fgets读取,并存储在变量line中。然后提取line中的每个子字符串(由空格或\t字符分隔),并通过for循环中的函数strtok将指向该子字符串的指针存储在p中(例如,在strtok上的进一步示例请参见此post )。
然后,函数只打印p,但是您可以在这里使用子字符串完成所有操作。我还计算(++count)在每一行中找到的项目数。最后,函数getline计数并返回读取的行数。
https://stackoverflow.com/questions/37700201
复制相似问题