开发者

fscanf() to take input

开发者 https://www.devze.com 2023-04-03 17:14 出处:网络
Here\'s my code: FILE* fp,*check; fp=fopen(\"file.txt\",\"r\"); check=fp; char polyStr[10]; while(fgetc(check)!=\'\\n\')

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消