除了计算我移动了多少个空格。是否有一种简单的方法可以将缓冲区恢复到行的开头进行读取?我试图读取字符串,然后回去读取不同的字符串和数字。它不按顺序所以我必须回去专门寻找它们。我该怎么做。
我使用rewind(fp);
,但这会回到文件的开头。
我也试图在字符串后读取整数。问题是难以读取双倍,三位数字。我能够做到。但是当你看到功能向下时,就会出现问题。是否有更简单的方法来读取多位整数;
void get_total(FILE*fp, int* ptotal, int* pscores, int* pnum_quiz){
char c;
int i = 0;
int total=0;
int digits;
int first, second, third;
*pnum_quiz = 0;
int number_of_conversions;
number_of_conversions = fscanf(fp, "%c", &c);
while (isdigit(c) || isspace(c) && c !='\n' && c !=NULL && number_of_conversions!=0 && number_of_conversions !=EOF){
if (isspace(c)){
number_of_conversions = fscanf(fp, "%c", &c);
}
else if (isdigit(c)){
first = c - '0'; // convert a character integer to integer
*(pscores + i) = first;
i++;
number_of_conversions = fscanf(fp, "%c", &c);
digits = 1;
if (isdigit(c)){
second = c - '0';
*(pscores + i) = second;
i++;
number_of_conversions = fscanf(fp, "%c", &c);
digits = 2;
if (isdigit(c)){
third = c - '0';
*(pscores + i) = third;
i++;
digits = 3;
}
else{
fseek(fp, -1, SEEK_CUR);
*(pscores + i) = -1;
i++;
}
}
else{
fseek(fp, -1, SEEK_CUR);
*(pscores + i) = -1;
i++;
*(pscores + i) = -1;
i++;
}
if (digits==3){
total = total + (first * 100) + (second * 10) + third;
}
else if (digits==2){
total = total + (first * 10) + second;
}
else {
total = total + first;
}
number_of_conversions = fscanf(fp, "%c", &c);
}
number_of_conversions = fscanf(fp, "%c", &c);
*pnum_quiz = *pnum_quiz + 1;
}
*ptotal = total;
}
答案 0 :(得分:2)
你可以fseek
向后浏览文件,但在我看来,这不是一个好的选择。
只需读入整行并将其存储在char
缓冲区中。你的代码通过重复调用fscanf(fp, "%c", &c)
来做到这一点,这是不必要的笨拙。已有一个函数可以执行此操作fgets
:
char line[80];
while (fgets(line, sizeof(line), fp) != NULL) {
// Now scan line instead of fp
}
现在,您可以根据您的输入格式解析line
:sscanf(line, ..)
如果您有固定格式。如果您需要提取令牌,请反复strtok
,依此类推。 (您没有显示输入的格式,但可能有一个函数来处理它比手动编码更好。)
fgets
的一个潜在问题是您需要指定最大长度,如果您可以拥有任意长的行,则可能不适合。还有每行末尾留下的新行字符的烦恼。