Here's my code:
FILE* fp,*check;
fp=fopen("file.txt","r");
check=fp;
char polyStr[10];
while(fgetc(check)!='\n')
{
fscanf(fp,"%s",polyStr);
puts(polyStr);
check=fp;
}
while(fgetc(check)!=EOF)
{
fscanf(fp,"%s",polyStr);
puts(polyStr);
check=fp;
}
Now if my file.txt
is:
3,3, 4,4, 5,5
4,1, 5,5, 12,2
Now output is:
,3,
4,4,
5,5,
,1,
5,5,
12,2,
开发者_运维技巧
Now why is the first character of both the lines not getting read?
Your fgetc
call is eating the character.
You should read entire lines with fgets
and then parse them with the strtol
family. You should never use any of the *scanf
functions.
Let's talk about the format of the input data first. Your list would seem to be better formatted if you only had <coef>,<exp>
without the trailing comma. In this way, you would have a nice pattern with which to match. So you could do something like:
fscanf(filep, "%d,%d", &coef, &exp)
to get the values. You should check the return value from fscanf to be sure that you are reading 2 fields. So if the format of a line was a set of the following '<coef>,<exp><white-space>
' (where white-space is either one blank or one newline, then you would be able to do the following:
do {
fscanf(filep, "%d,%d", &coef, &exp);
} while (fgetc(filep) != '\n');
This code allows you to get the pairs until you eat the end of line. The while conditional will eat either the blank or the newline. You can wrap this in another loop for processing several lines.
Note that I have NOT tested this code, but the gist of it should be clear. Comment if you have any more questions.
精彩评论