C:sscanf的问题 [英] C: sscanf problem
问题描述
嗨结果
我有这样一个文本文件:
Hi
I have a text file like this:
2结果
10 5结果
器B31 2结果
C 6 6
2
A 10 5
B 31 2
C 6 6
我想读一个变量结果第一行号
并读取3个变量的每一行的空格隔开3个值的列表。
我写这篇code:
I want to read first line number in a variable
and read each line's space separated list of 3 values in 3 variables.
I wrote this code:
iF=fopen(fileName,"r");
fgets(tmp,255,iF);
sscanf(tmp,"%d",&interval);
while(!feof(iF)){
cur=(P *)malloc(sizeof(P));
fgets(tmp,255,iF);
sscanf(tmp,"%c %d %d",&Name,&AT,&ET);
cur->jobName=Name;
cur->arrivalTime=AT;
cur->execTime=ET;
add_to_list(head,cur);
}
它可以正确处理行1,3,4而不是2号线!
在第2行它存储什么!
正如我在调试器检查一些奇怪的字符是在文件中(\\ 342 \\ 200 \\ 252),我不知道他们从哪儿来!?
It works correctly for lines 1,3,4 but not for line 2! in line 2 it stores nothing! As I check in Debugger some strange chars are in the file (\342\200\252) and I don't know where are they from!?
这是什么问题?
感谢
推荐答案
以下code为我工作:
The following code works for me:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
const char *fileName = "data.txt";
FILE *iF;
int interval;
char Name[256], tmp[256];
int AT, ET;
iF = fopen(fileName, "r");
if (fgets(tmp, 255, iF) == NULL)
goto error;
if (sscanf(tmp, "%d", &interval) != 1)
goto error;
while (fgets(tmp, 255, iF) != NULL) {
if (sscanf(tmp, "%c %d %d", Name, &AT, &ET) != 3)
goto error;
fprintf(stdout, "%s, %d, %d\n", Name, AT, ET);
}
return 0;
error:
fprintf(stderr, "error while reading from the file.\n");
return 1;
}
请注意多少code的专门用于错误处理。这是必要的。
Note how much of the code is dedicated to error handling. That's necessary.
这篇关于C:sscanf的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!