简体   繁体   中英

i am very confused about reading from txt file

sorry i'm new at ci want to read these data from txt file.

A 7
c 5
y 6
U 9
j 4
Z 3
z 5
0

here is my code

 while(feof(input)==0){
    char c;
    int num;
    fscanf(input,"%c%d",&c,&num);
    printf("%c:%d\n",c,num);
}

but result in console is not same as txt file the result is

Open file complete

A:7

:7
c:5

:5
y:6

:6
U:9

:9
j:4

:4
Z:3

:3
z:5

:0

my code is correct, isn't it?

 fscanf(input,"%c%d",&c,&num); 

my code is correct, isn't it

You're not eating the newlines. Change that to:

fscanf(input,"%c%d ",&c,&num);
                  ^

As explanation, each line ends with aa character, '\\n' . If you don't do anything about it, %c will try to read it and you'll get confusing results. A cheap trick is to add a blank space in fscanf which makes it eat all blanks after a %c%d couple.

EDIT

In light of comment from Peter Kowalski:

shouldn't it be fscanf(input,"%c %d ",&c,&num); ? I've put additional space between %c and %d

This is a very good question. Thing is %d is one of the specifiers that ignore leading space . No matter how many blanks are in the stream, scanf will eat and discard them. Therefore a blank before %d is implicit.

你还需要吃新线。

fscanf(input,"%c%d\n",&c,&num);

Quick fix: simply adjust your printf() statement from

 printf("%c:%d\n",c,num);

to

 printf("%c %d",c,num);

There are other ways, like adjusting your current scanf() , which is better as it fixes the problem at the source (you are reading and keeping the newline).

Alternatively you could just read the whole line without parsing it into components and print it out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM