新手请教一个小问题!
题目:输入一个正整数,然后读取n个正整数a1,a2,a3……,an,最后再读一个正整数m,统计a1,a2,……an中共有多少个整数的值小于m。提示:使用fopen
下面是我的代码:
#include <stdio.h>int main(){ FILE *fin,*fout,*fin2;//声明 fin = fopen("in.txt","rb");//这个用于读入n个整数与m fout = fopen("out.txt","wb");//用于写入之前读入的n个整数 fin2 = fopen("out.txt","rb");//用于读入被写入的n个整数 int n; scanf("%d",&n);//输入n int i; for(i = 0;i < n;i++){ int save; fscanf(fin,"%d",&save);//循环内依次读入fin中的整数,并保存进save变量 fprintf(fout,"%d ",save);//将save变量的值写入fout } int m,temp; int count = 0;//计数器 fscanf(fin,"%d ",&m);// 读入m printf("m:%d\n",m); while(fscanf(fin2,"%d",&temp) != EOF){//从fin2读入值,保存进temp、如果没有读到末尾,则循环继续 if(temp < m){//如果 temp小于m count++;//计数器增加 } } printf("%d",count); getch(); return 0;}#include <stdio.h>int main(){ FILE *fin,*fout,*fin2;//声明 fin = fopen("in.txt","rb");//这个用于读入n个整数与m fout = fopen("out.txt","wb");//用于写入之前读入的n个整数 fin2 = fopen("out.txt","rb");//用于读入被写入的n个整数 这里没有必要再弄一个读取的 int n; scanf("%d",&n);//输入n int i; for(i = 0;i < n;i++){ int save; fscanf(fin,"%d",&save);//循环内依次读入fin中的整数,并保存进save变量 fprintf(fout,"%d ",save);//将save变量的值写入fout } int m,temp; int count = 0;//计数器 fscanf(fin,"%d ",&m);// 读入m 这时候文件指针已经到最后了,你就读不出来什么了 printf("m:%d\n",m); while(fscanf(fin2,"%d",&temp) != EOF){//从fin2读入值,保存进temp、如果没有读到末尾,则循环继续 不能确定fin2的位置会不会受到fout的影响,但是最少要fseek把指针移到前面去 if(temp < m){//如果 temp小于m count++;//计数器增加 } } printf("%d",count); getch(); return 0;}
[解决办法]
出现这种情况,最好是调试一下,单步跟踪,看看变量值的变化。
[解决办法]
楼主看一下到那个while循环时,fin2的指针位置,是不是在文件末尾
[解决办法]
加断点,看每一步的变量的变换。还有就是建议楼主如果采用二进制的方式打开文件的话使用fwrite和fread比较好。以文本方式打开的话用fscanf比较好