简体   繁体   English

我对从txt文件中读取非常困惑

[英]i am very confused about reading from txt file

sorry i'm new at ci want to read these data from txt file. 对不起,我是新来的ci想从txt文件中读取这些数据。

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 但结果是控制台与txt文件的结果不一样

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' . 作为解释,每一行以一个字符'\\n'结尾。 If you don't do anything about it, %c will try to read it and you'll get confusing results. 如果你对它没有做任何事情, %c会尝试阅读它,你会得到令人困惑的结果。 A cheap trick is to add a blank space in fscanf which makes it eat all blanks after a %c%d couple. 一个便宜的技巧是在fscanf添加一个空格,这使得它在%c%d对之后吃掉所有空白。

EDIT 编辑

In light of comment from Peter Kowalski: 根据Peter Kowalski的评论:

shouldn't it be fscanf(input,"%c %d ",&c,&num); 不应该是fscanf(输入,“%c%d”,&c,&num); ? I've put additional space between %c and %d 我在%c和%d之间放了额外的空格

This is a very good question. 这个问题问得好。 Thing is %d is one of the specifiers that ignore leading space . 事情是%d忽略领先空间的说明者之一 No matter how many blanks are in the stream, scanf will eat and discard them. 无论流中有多少空白, scanf都会吃掉并丢弃它们。 Therefore a blank before %d is implicit. 因此%d之前的空白是隐含的。

你还需要吃新线。

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

Quick fix: simply adjust your printf() statement from 快速修复:只需调整printf()语句即可

 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). 还有其他方法,比如调整当前的scanf() ,这样可以更好地解决源代码问题(您正在阅读并保留换行符)。

Alternatively you could just read the whole line without parsing it into components and print it out. 或者,您可以只读取整行,而无需将其解析为组件并将其打印出来。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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