无法读取文件? [英] can't read file?

查看:77
本文介绍了无法读取文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码用于读取名为input.txt的文件

#include< stdio.h>

int main(int argc,char * argv []){

FILE * fp;

int ch;

fp = fopen(" input.txt"," r");

ch = fscanf(fp,"%d",& ch);

printf("%d \ n",ch) ;


fclose(fp);

返回0;

}


包含在input.txt中

3

3 14

2 8

-1 0

当我运行程序时输出为:

1


发生了什么?

为什么输出不是3?


尼克

解决方案

nick< i1 *** *****@yahoo.com>写道:

以下代码用于读取名为input.txt的文件
#include< stdio.h>
int main(int argc,char * argv []){
FILE * fp;
int ch;
fp = fopen(" input.txt"," r");
ch = fscanf(fp ,%d,& ch);
printf("%d \ n",ch);

fclose(fp);
返回0;
}

包含在input.txt中
3
3 14
2 8
-1 0

当我运行程序时输出结果是:
1

是怎么回事?
为什么输出不是3?




fscanf()返回扫描的项目数,在这种情况下,如果成功,则
为1。你正在传递& ch作为fcanf的参数()

*和*你将结果赋给ch。不要那样做。


(我不确定它是否会调用未定义的行为,但它确实不是你想要的b $ b要做的事。)


-

Keith Thompson(The_Other_Keith) ks * **@mib.org < http://www.ghoti.net/~kst>

圣地亚哥超级计算机中心< *> < http://users.sdsc.edu/~kst>

我们必须做点什么。这是事情。因此,我们必须这样做。


ch = fscanf(fp,"%d",& ch);

此行是答案!因为fscanf()返回一个int数字1,你的ch

得到它。

真正的方式是这样的

fscanf(fp,& ;%d",& ch);

写这样就好了,fscanf设置值为ch,你会发现

结果是3


祝你好运


usr_root


谢谢!

the following code is used to read a file called "input.txt"
# include <stdio.h>
int main(int argc,char *argv[]){
FILE *fp;
int ch;
fp=fopen("input.txt","r");
ch=fscanf(fp,"%d",&ch);
printf("%d\n",ch);

fclose(fp);
return 0;
}

the contains in "input.txt"
3
3 14
2 8
-1 0
when i run the program the output is:
1

what''s going on?
why the output is not 3?

Nick

解决方案

nick <i1********@yahoo.com> writes:

the following code is used to read a file called "input.txt"
# include <stdio.h>
int main(int argc,char *argv[]){
FILE *fp;
int ch;
fp=fopen("input.txt","r");
ch=fscanf(fp,"%d",&ch);
printf("%d\n",ch);

fclose(fp);
return 0;
}

the contains in "input.txt"
3
3 14
2 8
-1 0
when i run the program the output is:
1

what''s going on?
why the output is not 3?



fscanf() returns the number of items scanned, which in this case will
be 1 if it succeeds. You''re passing &ch as an argument to fcanf()
*and* you''re assigning the result to ch. Don''t do that.

(I''m not certain whether it invokes undefined behavior, but it''s
certainly not what you want to do .)

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.


ch=fscanf(fp,"%d",&ch);
this line is the answer! because fscanf() return a int number 1,your ch
got it.
the true way was like this
fscanf(fp,"%d",&ch);
write like this is all ok,fscanf set value to ch,and you will found
the result is 3

best wishes

usr_root


thanks!


这篇关于无法读取文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆