fflush 清空缓冲区

合集下载

C语言综合性设计实验报告

C语言综合性设计实验报告

C语言综合性设计实验报告1.实验题目建立一个简单的会员卡储值积分管理系统。

该系统的主要功能是:会员卡管理功能和会员卡储值积分管理。

会员卡管理功能:(1)根据身份证办理会员卡,一张身份证只能办理一张会员卡。

(2)根据需要可以注销、挂失、冻结会员卡或修改会员卡密码以及积分和消费金额查询。

会员基本信息包括:会员身份证号、卡号、密码、积分、消费金额、级别。

会员卡储值积分管理:(1)根据会员卡级别设置折扣率,根据折扣率自动打折计算消费金额。

(2)根据消费金额计算积分,积分累计达到一定标准后换购商品。

2.设计分工组员组员组员:组员在本系统开发中,小组各成员的分工如下:会员的信息存储数据结构和各个子函数的名称及实验报告的书写由全体成员统一制定;主函数main,主控程序模块call函数,系统退出函数,各函数名称及用到的变量名称的规定由胡丽萍统一负责。

会员管理总函数,会员积分总函数,会员信息查询函数及信息内容输出函数由陈建飞负责。

会员信息冻结函数,挂失函数,注销函数及内部返回到主菜单的返回函数由郭娟如负责。

密码设置函数,查询时检查函数,增加新会员函数,修改密码函数统一由郭霞负责。

输入级别函数,输入消费函数,查询积分函数,查询折扣率函数统一交由胡桂芳负责。

3.问题概述要实现这个会员积分管理系统,要遇到的问题如下:①. 首先要有一个主函数来负责对子函数的调用。

②. 进行新增一个会员时的增加操作③. 对身份证号码的判定操作及密码的设置及判定操作④. 输出会员信息时对各部分的总体把握⑤. 修改密码时覆盖其原有的密码⑥. 会员级别及消费来查询折扣率和积分的操作4.问题分析首先该问题分为两个大块,一个是会员卡管理功能,另一个是会员积分管理功能。

针对会员卡管理功能,首先应具备7项功能,新会员的录入,查询会员的信息,会员的挂失操作,会员的冻结操作,修改密码的操作,注销会员的操作,以及返回上一层目录的操作。

在没有一个会员的时候,如果用户进行了查询及注销等其他在有用户基础上才应该进行的操作,也应该给出相应的提示,来警示用户应该正确的操作。

c语言的系统删除命令

c语言的系统删除命令

c语言的系统删除命令C语言-模拟系统寻找并删除文件//C语言-模拟系统寻找并删除文件#includevoidfunc(chars[],intc)//删除的函数{char*q=s;for(;*q!='\0';q++)if(*q!=c)*(s++)=*q;*s=0;}intmain()//范志军{charstr[]="abcabcabc";//文件夹中有很多文件charch;//接收要寻找的文件charah;//删除文件的字符inti,j=0;//循环变量,统计文件出现次数printf("原文件夹里面有:%s\n",str);printf("请输入你要寻找并删除的文件:\n"); scanf("%c",&ch);//输入的字符相当于文件名fflush(stdin);//清空缓冲区for(i=0;str[i]!='\0';i++)//文件夹中遍历if(str[i]==ch)printf("文件夹中出现%c文件%d次\n",ch,++j); if(j==0)printf("文件夹中没有%c文件\n",ch);if(j>0)//表示已经寻找到某文件{printf("你确定要删除%c文件(Y/N):\n"); scanf("%c",&ah);if(ah=='y'||ah=='Y')func(str,ch);printf("没有删除的文件有:%s\n",str);}return0;}。

C语言程序设计教程 李含光 郑关胜 清华大学出版社习题答案

C语言程序设计教程 李含光 郑关胜 清华大学出版社习题答案

第1章习题参考答案1.单项选择题(1) A (2) C (3) D (4) C (5)B2.填空题(1)函数(2)主函数(main)(3)printf() ,scanf()第2章习题参考答案1.单项选择题(1) C (2) B (3) C (4) C (5)C(6) C (7)D (8) C (9) D (10)C(11) D (12)B (13) B2.填空题(1)1(2)26(3)6 ,4 , 2(4)10 , 6(5)3.000000(6)双精度(double)(7)9(8)字母,数字,下划线(9)13.700000(10)11(11)((m/10)%10)*100+(m/100)*10+m%10(12)0(13)10 ,9 ,11(15)(x<0&&y<0)||(x<0&&z<0)||(y<0||z<0 )(16)double (17)x==0(18)sqrt(fabs(a-b))/(3*(a+b))(19)sqrt((x*x+y*y)/(a+b))第3章习题参考答案1.单项选择题(1) C (2) C (3) C (4) D (5)D(6) B (7)C (8) D (9) B (10)C(11) B (12)C (13) B (14) B (15)B(16) A2.填空题(1)用;表示结束(2){ }(3)y=x<0?1:x==0?0:-1(4)y%4==0&&y%100!=0||y%400==0(5)上面未配对(6)default标号(7)while ,do while ,for(8)do while(9)本次(10)本层3.阅读程序,指出结果(1)yes(2)*&(3)ABother(4)28 70(5)2,0(6)8(7)36(8)1(9)3,1,-1,3,1,-1(10)a=12 ,y=12(11)i=6,k=4(12)1,-24.程序填空(1)x:y ,u:z(2)m=n ,m!=0 ,m=m/10(3)t<eps , t*n/(2*n+1) , printf(“%lf\n”,2*s)(4)m%5==0 ,printf(“%d\n”,k)(5)cx=getchar() , cx!=front , cx(6)double s=0 , 1.0/k , %lf(7)s>=0 , s<gmin ,5.编程题(1).#include <stdio.h>int main(){double x,y;scanf("%lf",&x);if(x<1)y=x;else if(x>=1.0&&x<10)y=2*x-11;elsey=3*x-11;printf("%lf\n",y);return 0;} (2).#include <stdio.h>int main(){double x,y,z,min;scanf("%lf%lf%lf",&x,&y,&z);if(x>y)min=y;elsemin=x;if(min>z)min=z;printf("min=%lf\n",min);return 0;}(3).#include <stdio.h>int main(){int y,m,d,flag,s=0,w,i;scanf("%d%d%d",&y,&m,&d);flag=(y%4==0&&y%100!=0||y%400 ==0);w=((y-1)*365+(y-1)/4-(y-1)/100+(y-1)/400)%7;for(i=1;i<=m;i++){switch(i){case 1:s=d;break;case 2:s=31+d;break;case 3:s=59+d;break;case 4:s=90+d;break;case 5:s=120+d;break;case 6:s=151+d;break;case 7:s=181+d;break;case 8:s=212+d;break;case 9:s=243+d;break;case 10:s=273+d;break;case 11:s=304+d;break;case 12:s=334+d;break;}}if(flag==1&&m>2)s=s+1;s=(w+s)%7;if(s==0)printf("星期日\n");elseprintf("星期%d\n",s);return 0;}(4).#include <stdio.h>int main(){float p,r;scanf("%f",&p);if(p<=10)r=p*0.1;else if(p>10&&p<=20)r=10*0.1+(p-10)*0.075;else if(p>20&&p<=40)r=10*0.1+10*0.075+(p-20)*0.05;else if(p>40&&p<=60)r=10*0.1+10*0.075+20*0.05+(p-40) *0.03;else if(p>60&&p<=100)r=10*0.1+10*0.075+20*0.05+20*0.0 3+(p-60)*0.015;else if(p>100)r=10*0.1+10*0.075+20*0.05+20*0.0 3+40*0.015+(p-100)*0.01;printf("%f\n",r);return 0;}(5).#include <stdio.h>int main(){char c;while((c=getchar())!='\n'){if(c>='a'&&c<='z')c=c-32;putchar(c);}return 0;}(6).#include<stdio.h>int main(){int m,k=2;printf("输入一个正整数:\n");scanf("%d",&m);while(k<m)if(m%k==0){printf("%4d",k);m=m/k;}elsek++;printf("%4d\n",m);return 0;}(7).#include<stdio.h>int main(){int a,n,s=0,p=0,i;scanf("%d %d",&n,&a);for(i=1;i<=n;i++){p=p*10+a;s=s+p;}printf("%d\n",s);return 0;}(8).#include<stdio.h>int main(){int i,j,k;for(i=1;i<=9;i++)for(j=0;j<=9;j++)for(k=0;k<=9;k++)printf("%5d",100*i+10*j+k);return 0;}(9).#include<stdio.h>#include<math.h>int main(){float a=-10,b=10,x,f1,f2,f;f1=(((2*a-4)*a+3)*a)-6;f2=(((2*b-4)*b+3)*b)-6;do{x=(a+b)/2;f=(((2*x-4)*x+3)*x)-6;if(f*f1<0){b=x;f2=f;}else{a=x;f1=f;}}while(fabs(f)>=1e-6);printf("%6.2f\n",x);return 0;}(10).#include<stdio.h>#include<math.h>int main(){int n=2;double eps,t,s=0,x;scanf("%lf %lf",&x,&eps);t=x;s=t;while(fabs(t)>=eps){t=-t*(2*n-3)*x*x/(2*n-2);s=s+t/(2*n);n++;}printf("%d,%lf\n",n,s);return 0; (11).#include<stdio.h>int main(){unsigned long s,t=0,p=1;scanf("%u",&s);while(s!=0){if((s%10)%2!=0){t=t+(s%10)*p;p=p*10;}s=s/10;}printf("%u\n",t);return 0;}第4章习题参考答案1.单项选择题(1) D (2) D (3) D (4) B (5)D(6) B (7)A (8) D (9) C (10)D(11) B (12)D (13) A (14) B2.填空题(1)2(2)嵌套,递归(3)全局变量,局部变量,静态变量,动态变量(4)auto , static , register , extern(5)外部变量(6)编译,运行3.阅读程序,指出结果(1)15(2)5(3)5,4,3(4)i=5i=2i=2i=4i=2(5)求水仙花数(6)-5*5*5(7)30(8)0 101 112 124.程序填空(1)float fun(float , float) ,x+y,x-y , z+y,z-y(2)x ,x*x+1(3)s=0 , a=a+b5.编程题(1).#include<stdio.h>unsigned int fun(unsigned int);int main(){unsigned int s;scanf("%u",&s);printf("%u\n",fun(s));return 0;}unsigned int fun(unsigned int s){unsigned int p=0;while(s!=0){p=p+s%10;s=s/10;}return p;}(2).#include<stdio.h>#include<stdlib.h>#include<math.h>void f1(float,float,float,float);void f2(float,float,float,float);voidf3(float,float,float,float);int main() {float a,b,c,d;scanf("%f %f %f",&a,&b,&c);if(a==0){printf("不是一元二次方程\n");exit(0);}d=b*b-4*a*c;if(d>0)f1(a,b,c,d);else if(d==0)f2(a,b,c,d);elsef3(a,b,c,d);return 0;}void f1(float a,float b,float c,float d){ float x1,x2;{x1=(-b+sqrt(d))/(2*a);x2=(-b-sqrt(d))/(2*a);printf("%.2f ,%.2f\n",x1,x2);}}void f2(float a,float b,float c,float d){ float x1,x2;{x1=-b/(2*a);x2=-b/(2*a);printf("%.2f ,%.2f\n",x1,x2);}}void f3(float a,float b,float c,float d){ float x1,x2;{x1=-b/(2*a);x2=sqrt(-d)/(2*a);printf("%.2f+i*%.2f\n",x1,x2);printf("%.2f-i*%.2f\n",x1,x2);}}(3).#include<stdio.h>double p(int,double);int main(){int n;double x;do{scanf("%d",&n);}while(n<0);scanf("%lf",&x);printf("%lf\n",p(n,x));return 0;}double p(int n,double x){double pn;if(n==0)pn=1;else if(n==1)pn=x;elsepn=((2*n-1)*x*p(n-1,x)-(n-1)*p(n-2, x))/n;return pn;}(4).#include<stdio.h>#define RATE 0.053double fun(float);void display(float,int);int main(){float dep;int season;scanf("%f %d",&dep,&season);display(dep,season);return 0;}double fun(float d){return d*RATE;}void display(float d,int s){int i;printf("季度利息余额\n");printf("-------------------------------\n");for(i=1;i<=s;i++){printf("%-4d %-.2f %-.2f\ n",i,fun(d),fun(d)*i+d);printf("-------------------------------\n");} }(5).#include<stdio.h>double fun(void);int main(){printf("%lf\n",fun());return 0;}double fun(void){double s=0;int n=1;while((double)(2*n-1)/((2*n)*(2*n)) >1e-4){s=s+(double)(2*n-1)/((2*n)*(2*n));n++;}return s;}(6).#include<stdio.h>int fun(int);int main(){int w;scanf("%d",&w);printf("%d\n",fun(w));return 0;}int fun(int w){int n=1,p=1,m;m=w;while(m>10){m=m/10;p=p*10;n++;}return w%p;}第5章习题参考答案1、选择题:(1) C (2) B C (3) B (4) B (5) A(6) D (7) D (8) B2、填空题(1)0,9(2)float realArray[100],char strArray[16],int intArray[1000](3)运算符sizeof(4)6字节3、阅读程序,写出下面程序的运行结果(1)aabbcc dd(2)abcd(3)ahAMa(4)0010(5)1 3 4 5(6)This is the title.Name 1 is RosalindaName 2 is ZekeThe biggest name alpabetically is ZekeBoth names are Rosalinda Zeke(7)0 0 0 0 0 0 0 00 1 2 3 4 5 6 70 2 5 6 8 10 748 140 3 6 9 12 15 18 210 4 8 12 16 20 24 280 5 10 15 20 177 30 350 6 12 18 24 30 36 420 7 14 21 28 35 42 494、程序填空(1)a[i][j] != a[j][i] , 1(2)0, a[i] < a[mini] , maxi = i , a[maxi] = a[mini](3)int a[], int b[], b[i] = a[i], -999, arraycopy(a,b), b[i++](4)a<sizeof(ch), if5、编程题(1)#include<stdio.h>int main ( ){1 int a[3][4] = {0, 2,9,7,5,13,6,8,27,11,1,3};int i,j,temp;for(i=0,j=0;j<4;j++){temp = a[2-i][j];a[2-i][j] = a[i][j];a[i][j] = temp;}for(i=0;i<3;i++){for(j=0;j<4;j++)printf("%3d",a[i][j]);printf("\n");}return 0;}(2)#include<stdio.h>int main ( ){static int a[6][6];int i,j,t=1;for(i=0;i<6;i++){t = i+1;for(j=0;j<i+1;j++)a[i][j] = t--;}for(i=0;i<6;i++){for(j=0;j<6;j++)printf("%3d",a[i][j]);printf("\n");}return 0;}(3)#include <stdio.h>#define M 3#define N 4#define R 5int main( ){static int a[M][N],b[N][R],c[M][R];int i,j,k;2 printf("Matrix a:\n");for( i = 0; i < M; i++ )for( j = 0; j < N; j++ )scanf( "%d",&a[i][j] );printf("Matrix b:\n");for( i = 0; i < N; i++ )for( j = 0; j < R; j++ )scanf( "%d",&b[i][j] );for( i = 0; i < M; i ++ )for( j = 0; j < N; j++ )for( k = 0; k < R; k++)c[i][k] += a[i][j]*b[j][k];for( i = 0; i < M; i++ ){for( j = 0; j < R; j++ )printf( "%3d",c[i][j] );printf("\n");}return 0;}(4)#include <stdio.h>#define M 5int main( ){static int a[M];int i,max = -1,min = 100,maxi,mini,temp;for( i = 0; i < M; i++ )scanf( "%d",&a[i] ); //0~99间的值for( i = 0; i < M; i++ ){if( max < a[i] ){max = a[i];maxi = i;}if( min > a[i] ){min = a[i];mini = i;}}temp = a[maxi];a[maxi] = a[mini];a[mini] = temp;for( i = 0; i < M; i++ )printf( "%3d",a[i] );return 0; }3(5)#include <stdio.h>#define M 3#define N 4int main( ){static int a[M][N];int max = -1,sumcol=0,sumrow=0;int i,j,maxi,col;for( i = 0; i < M; i++ ){sumrow = 0;for( j = 0; j < N; j++ ){scanf( "%d",&a[i][j] );sumrow += a[i][j];}if ( max < sumrow ){max = sumrow;maxi = i;}}printf("which col sum will be caculated?(>0)");scanf("%d",&col);for( i = 0; i < M; i ++ )sumcol += a[i][col-1];printf("The %dth row's sum is max, max=%d\n",maxi+1,max);printf("The %dth column's sum=%d\n",col,sumcol);return 0;}(6)#include <stdio.h>#define M 81int main( ){static char str[M];int i,count = 0;char ch;gets(str);fflush(stdin); //清空输入缓冲区,以便读入字符数据printf("Which character will be found?");ch = getchar();for( i = 0; i < strlen(str); i++ )if( ch == str[i] )count++;printf( "The number of character '%c' is %d\n",ch,count );4 return 0;}(7)#include <stdio.h>#include <stdlib.h>#define N 10 //同学人数#define M 5 //课程数void enter_scores(void);void sort_scores(int score[][M], int average[N][3]);void disp_scores(int score[][M]);void histogram(int n, int score[][M]);void printchar(int n); static int score[N][M];static int aver[N][3]; //第1列为均值,第2列原始顺序,第3列为均值逆序int main(){int course;enter_scores();printf("\n===========Oringenal Score Start=========\n");disp_scores(score);printf("\n===========Oringenal Score End===========\n");printf("\n===========Sorted Score Start============\n");sort_scores(score,aver);printf("\n===========Sorted Score End==============\n");printf("\nWhich class will be statisticed?\n");scanf("%d",&course);histogram(course, score);system("Pause");return 0;}/* 输入成绩*/void enter_scores(){int i, j;for(i=0; i<N; i++) {for(j=0; j<M; j++){scanf("%d",&score[i][j]);aver[i][0] += score[i][j];}}for( i = 0; i < N; i++ )for ( j = 1; j < 3; j++ )5 aver[i][j] = i;}/* 成绩排序. */void sort_scores(int score[][M], int average[N][3]){int i,j,t;int temp,tempindex;for( i = 0; i < N - 1; i++ )for( j = 0; j < N - 1 - i; j++ )if ( average[j][0] < average[j+1][0] ){temp = average[j][0];average[j][0] = average[j+1][0];average[j+1][0] = temp;tempindex = average[j][2];average[j][2] = average[j+1][2];average[j+1][2] = tempindex;}printf("\n Score1 Score2 Score3 Score4 Score5\n");for( i = 0; i < N; i++ ){t = average[i][2];for( j = 0;j < M; j++ ){printf("%8d", score[t][j]);}printf("\n");}}/* 输出成绩*/void disp_scores(int score[][M]){int i, j;printf("\n Score1 Score2 Score3 Score4 Score5\n");for( i = 0; i < N; i++ ){for( j = 0;j < M; j++ )printf("%8d", score[i][j]);printf("\n");}}void printchar(int n){6 int i;for (i = 0; i < n; ++i) putchar('*');}void histogram(int course, int score[][M]){int i,temp;int segs[5] = {0};int sc[N];for( i = 0; i < N; i++ )sc[i] = score[i][course];for (i = 0; i < N; i++)/* 统计各分段人数*/{temp = (int)sc[i]/10;segs[ temp<6?0:temp-5]++; /* 成绩/10,将成绩分段*/}printf("\nSegment Number\n");for (i = 0; i < 5; i++) /* 输出直方图,每段的人数*/{printf("<%3d: %5d| ", (i+1)*10+50, segs[i]);printchar(segs[i]);putchar('\n');}putchar('\n');}(8)#include <stdio.h>#define M 81int main( ){static char str[M];int i,count = 0;char ch = 0;gets(str);for( i = 0; i < strlen(str); i++ )if( ch < str[i] )ch = str[i];for( i = 0; i < strlen(str); i++ )if( ch == str[i] )count++;printf( " max = '%c' ,count = %d\n",ch,count );return 0;}7第6章习题参考答案1、选择题:(1) B (2)B (3)D (4) D (5) A(6) C (7) C (8)A (9) B (10)D(11)C (12)B (13)C (14)D (15)A (16)A2、填空题(1)常量,变量(2)指针(3)2(4)12,12(5)a[0],a[3]3、阅读程序,写出下面程序的运行结果(1)5(2)6(3)abcdefglkjih(4)976531(5)5,9(6)2,4,5,7,6,0,11,9,7,3,(7)string_a=I am a teacher.string_b=You are a student.string_a=I am a teacher.string_b=I am a teacher.4、程序填空(1)*p != '\0', *p-'0', j—(2)i <strlen(str), j=i, k+1(3)a+i, (char)(n%10) + '0'(4)*pk = i, a,n,i+1,pk(5)s1++, *s2, s1=p5、编程题(1)#include <stdio.h>int main(){int a=3,b=7,c=2;int *ptra = &a,*ptrb = &b,*ptrc = &c;int temp;printf("a=%d,b=%d,c=%d\n",a,b,c);printf("*ptra=%d,*ptrb=%d,*ptrc=% d\n",*ptra,*ptrb,*ptrc);if ( *ptra > *ptrb ){temp = *ptra;*ptra = *ptrb;1 *ptrb = temp;}if ( *ptra > *ptrc ){temp = *ptra;*ptra = *ptrc;*ptrc = temp;}if ( *ptrb > *ptrc ){temp = *ptrb;*ptrb = *ptrc;*ptrc = temp;}printf("a=%d,b=%d,c=%d\n",a,b,c); printf("*ptra=%d,*ptrb=%d,*ptrc=% d\n",*ptra,*ptrb,*ptrc);return 0;}(2)#include <stdio.h>#include <stdlib.h>void inputdata(int a[],int n);void process(int a[],int n);void outputdata(int a[],int n);int main(){int a[10],n=10;inputdata(a,n);outputdata(a,n);process(a,n);outputdata(a,n);system("Pause");return 0;}void inputdata(int a[],int n) //0~99之间的数{int i;for( i = 0; i < n; i++ )scanf("%d",a+i);}void outputdata(int *ptr,int n){int i;2printf("\n==========OutPut Data Start=============\n");for( i = 0; i < n; i++ )printf("%4d",*ptr++);printf("\n==========OutPut Data End================\n");}void process(int *ptr,int n){int i,maxi,mini;int max=-1,min=101;for( i = 0; i < n; i++ ){if ( max < *(ptr+i) ){max = *(ptr+i);maxi= i;}if ( min > *(ptr+i) ){min = ptr[i];mini= i;}}if ( mini != 0){i = ptr[0];ptr[0] = ptr[mini];ptr[mini] = i;}if (maxi != n-1){i = ptr[n-1];ptr[n-1] = ptr[maxi];ptr[maxi] = i;}if (maxi == 0 && mini == n-1){i = ptr[maxi];ptr[maxi] = ptr[mini];ptr[mini] = i;}}(3)#include<stdio.h>3int strLength (char *);int main(){static char str[81];gets(str);printf("string "%s" length:%3d\n",str,strLength(str)) ;system("Pause");return 0;}int strLength (char *s){char *p=s;while (*p) p++ ;return (p-s) ;}(4)#include <stdio.h>#define M 3#define N 4void Transpose (int (*a)[N],int (*T)[M]);int main( ){static int a[M][N],T[N][M];int i,j;for( i = 0; i < M; i++ )for( j = 0; j < N; j++ )scanf( "%d",&a[i][j] );printf("\n======Oringinal Matrix Start=========\n");for( i = 0; i < M; i ++ ){for( j = 0; j < N; j++ )printf( "%4d",a[i][j] );printf("\n");}printf("\n======Oringinal Matrix End===========\n");Transpose(a, T);printf("\n======Transpose Matrix Start=========\n");for( i = 0; i < N; i ++ ){for( j = 0; j < M; j++ )printf( "%4d",T[i][j] );printf("\n");}4printf("\n======Transpose Matrix End===========\n");return 0;}void Transpose (int (*a)[N],int (*T)[M]){int i,j;for( i = 0; i < N; i++ )for( j =0; j < M; j++ )T[i][j] = a[j][i];}(5)#include <stdio.h>int main(){static char source[81],target[81];int result;gets(source);gets(target);result = Strcmp(source,target);if (result){if( result < 0 )printf("%s< %s\n",source,target);elseprintf("%s > %s\n",source,target);}elseprintf("%s= %s\n",source,target);return 0;}int Strcmp(char *s,char *t){while (*s && *t && (*s == *t)){s++;t++;}return *s - *t;}(6)#include <stdio.h>5#define M 5#define N 3int sum (int *a);int main( ){static int a[M][N];int i,j;for( i = 0; i < M; i++ )for( j = 0; j < N; j++ )scanf( "%d",&a[i][j] );for( i = 0; i < M; i ++ )printf("Row %d sum: %3d\n", i, sum(a[i]));return 0;}int sum (int *ptr){int i,result = 0;for( i = 0; i < N; i++ )result += *(ptr+i);return result;}6第7章习题答案1、选择题:(1)C (2) C (3)D (4) B (5)A(6)C (7) B (8) A (9)D (10)B(11)D (12) D (13) A2、判断题(1)×(2)√(3)√(4)×(5)√(6)×(7)√(8)×(9)√(10)√第8章习题答案1、选择题:(1) C (2) D (3)A (4) A (5) D(6) C (7) D (8) B 2、填空题(1).(成员域访问运算符),-〉(成员域间接访问运算符)(2)4, 6.0(3)enum(4)typedef(5)<person+3, old=p->age, q->name,q->age3、阅读程序,写出下面程序的运行结果(1)p!=NULL, c++, p->next(2)p1->next, p1->next, p1->next4、程序阅读题(1)7,3(2)zhangping 20(3)Li:3Zhang:3Wang:25.编程题#include <stdio.h>#include <stdlib.h>#define N 10 /*学生人数*/#define M 3 /* 课程数*/struct stu{ /*定义结构体类型*/char name[15];char num[6];float score[M];float aver;} student[N]; /*说明结构体变量*/struct stu findmax(struct stu student[]);void input(struct stu student[]);void output(struct stu student[]);int main(){struct stu temp;input(student);output(student);temp = findmax(student);printf("Max is:\n");printf("%15s%8s%7.2f%7.2f%7.2f% 7.2f",,temp.num,1temp.score[0],temp.score[1],temp.sc ore[2],temp.aver/M);system("Pause");return 0;}struct stu findmax(struct stu student[]){float max = 0.0;int i,maxi;for(i=0; i<N; i++){if(max < student[i].aver){max = student[i].aver;maxi = i;}}return student[maxi];}void input(struct stu student[]){int i,j;printf("input data:\n");for( i=0;i<N;i++){scanf("%s %s",student[i].name,stude nt[i].num);student[i].aver = 0;for( j=0;j<M;j++){scanf("%f",&student[i].score[j]);student[i].aver += student[i].score[j];}}}void output(struct stu student[]){int i,j;for( i=0;i<N;i++){printf("%15s%8s",student[i].name,stu dent[i].num);for( j=0;j<M;j++)printf("%7.2f",student[i].score[j]);printf("%7.2f\n",student[i].aver/M);}}2第9章习题答案1、选择题:(1) A (2) D (3)B (4) B (5) A(6) A (7) C (8)D (9) A (10) A2、填空题(1)文本文件,二进制文件(2)fopen, fclose(3)fprintf, fscanf, feof(4)fwrite, fread, fputs, fgets(5)文本, 二进制(6)1,0(7)字节,流式3、程序填空题(1)*fp1, *fp2, ftell(fp1); fgetc(fp1),fp2(2)*fp, fp,sizeof(stud[0])*i,0&stud[i](3)“r”, fgetc(fp),count++(4)FILE *f, sizeof(r), r.num,r.total4、编程题#include <stdio.h>#define N 5 /*学生人数*/#define M 3 /* 课程数*/struct stu{ /*定义结构体类型*/char name[15];char num[6];float score[M];float aver;} student[N]; /*说明结构体变量*/void sort(struct stu student[]);void writetofile(struct stu student[], char filename[],char mode[]);int main(){FILE *fp;struct stu *ptr=NULL;int i,j;printf("input data:\n");for( i=0;i<N;i++){scanf("%s %s",student[i].name,stude nt[i].num);student[i].aver = 0;for( j=0;j<M;j++){scanf("%f",&student[i].score[j]);student[i].aver += student[i].score[j];1 }}writetofile(student, "student.txt","w");writetofile(student, "sort.txt","w");writetofile(student,"sort2.txt","w");sort(student);writetofile(student, "sort.txt","a");ptr = (struct stu *)malloc(sizeof(struct stu));scanf("%s %s", ptr->name,ptr->num);ptr->aver = 0;for( j=0;j<M;j++){scanf("%f",&ptr->score[j]);ptr->aver += ptr->score[j];}if((fp=fopen("sort2.txt","a"))==NULL){printf("cannot open file");exit(0);}fprintf(fp,"%s %s",ptr->name,ptr->nu m);for( j=0;j<M;j++)fprintf(fp,"%7.2f",ptr->score[j]);fprintf(fp,"%7.2f\n",ptr->aver/M);fclose(fp);return 0;}void sort(struct stu student[]){struct stu temp;int i,j,k;for(i=0; i<N-1; i++){k=i;for(j=i+1; j<N; j++)if(student[j].aver < student[k].aver)k=j;if(k!=i){temp=student[i];student[i]=student[k];student[k]=temp;}}}2void writetofile(struct stu student[], char filename[],char mode[]){FILE *fp;int i,j;if((fp=fopen(filename,mode))==NULL ){printf("cannot open file");exit(0);}for( i=0;i<N;i++){ fprintf(fp,"%s %s",student[i].name,st udent[i].num);for( j=0;j<M;j++)fprintf(fp,"%7.2f", student[i].score[j]);fprintf(fp,"%7.2f\n",student[i].aver/M );}fclose(fp);}。

C C++ 误区—— fflush(stdin)

C C++ 误区—— fflush(stdin)

C/C++ 误区—— fflush(stdin)作者:antigloss1. 为什么 fflush(stdin) 是错的首先请看以下程序:程序代码#i nclude<stdio.h>int main( void ){int i;for (;;) {fputs("Please input an integer: ", stdout);scanf("%d", &i);printf("%d\n", i);}return 0;}这个程序首先会提示用户输入一个整数,然后等待用户输入,如果用户输入的是整数,程序会输出刚才输入的整数,并且再次提示用户输入一个整数,然后等待用户输入。

但是一旦用户输入的不是整数(如小数或者字母),假设 scanf 函数最后一次得到的整数是 2 ,那么程序会不停地输出“Please input an integer: 2”。

这是因为 scanf("%d", &i); 只能接受整数,如果用户输入了字母,则这个字母会遗留在“输入缓冲区”中。

因为缓冲中有数据,故而 scanf 函数不会等待用户输入,直接就去缓冲中读取,可是缓冲中的却是字母,这个字母再次被遗留在缓冲中,如此反复,从而导致不停地输出“Please input an integer: 2”。

也许有人会说:“居然这样,那么在 scanf 函数后面加上‘fflush(stdin);’,把输入缓冲清空掉不就行了?”然而这是错的!C和C++的标准里从来没有定义过 fflush(stdin)。

也许有人会说:“可是我用 fflush(stdin) 解决了这个问题,你怎么能说是错的呢?”的确,某些编译器(如VC6)支持用 fflush(stdin) 来清空输入缓冲,但是并非所有编译器都要支持这个功能(gcc3.2不支持),因为标准中根本没有定义 fflush(stdin)。

C语言中fflush(stdin)的作用

C语言中fflush(stdin)的作用

C/C++ 误区二:fflush(stdin)来源:蚂蚁的 C/C++ 标准编程作者:antigloss 等级:精品发布于2005-10-22 13:56 被读9885次【字体:大中小】今天看程序时,遇到了fflush()这个函数,以前从没有接触过,google了一下,发现这个篇文章介绍的很详细,贴上来和大家共享一下。

Antigloss 最后修改于 2006-11-251. 为什么 fflush(stdin) 是错的首先请看以下程序:#include <stdio.h>int main( void ){int i;for (;;) {fputs("Please input an integer: ", stdout);scanf("%d", &i);printf("%d\n", i);}return 0;}这个程序首先会提示用户输入一个整数,然后等待用户输入,如果用户输入的是整数,程序会输出刚才输入的整数,并且再次提示用户输入一个整数,然后等待用户输入。

但是一旦用户输入的不是整数(如小数或者字母),假设 scanf 函数最后一次得到的整数是 2 ,那么程序会不停地输出“Please input an integer: 2”。

这是因为 scanf("%d", &i); 只能接受整数,如果用户输入了字母,则这个字母会遗留在“输入缓冲区”中。

因为缓冲中有数据,故而 scanf 函数不会等待用户输入,直接就去缓冲中读取,可是缓冲中的却是字母,这个字母再次被遗留在缓冲中,如此反复,从而导致不停地输出“Please input an integer: 2”。

也许有人会说:“居然这样,那么在 scanf 函数后面加上‘fflush(stdin);’,把输入缓冲清空掉不就行了?”然而这是错的!C和C++的标准里从来没有定义过 fflush(stdin)。

C语言编程—清空键盘缓冲区,Linux和Windows下完美实现

C语言编程—清空键盘缓冲区,Linux和Windows下完美实现

C语言编程—清空键盘缓冲区,Linux和Windows下完美实现清空键盘缓冲区很多种方法,如用fflush(stdin);rewind(stdin);等,但是在linux这些都不起作用,还得我今天试了半天都没成功,上网搜了一下发现setbuf(stdin, NULL);就能直接清空键盘缓冲区了。

以下几个实例:Sample one1 2 3 4 5 6 7 8 9101112 #include <stdio.h>int main(){char ch1;char ch2;ch1 = getchar(); ch2 = getchar(); printf("%d %d",ch 1, ch2);return0;}程序的本意很简单,就是从键盘读入两个字符,然后打印出这两个字符的ASCII码值。

可是执行程序后会发现出了问题:当从键盘输入一个字符后,就打印出了结果,根本就没有输入第二个字符程序就结束了。

例如用户输入字符’a', 打印结果是97,10。

这是为什么呢?【分析】:scanf()和getchar()函数是从输入流缓冲区中读取值的,而并非从键盘(也就是终端)缓冲区读取。

而读取时遇到回车(n)而结束的,这个n会一起读入输入流缓冲区的,所以第一次接受输入时取走字符后会留下字符n,这样第二次的读入函数直接从缓冲区中把n取走了,显然读取成功了,所以不会再从终端读取!其实这里的10恰好是回车符!这就是为什么这个程序只执行了一次输入操作就结束的原因!【解决办法】:清空缓冲区的残留数据。

使用fflush(stdin); 或rewind(stdin); 均可起到清空键盘缓冲区的作用,这两个函数均包含在stdio.h这个头文件中修正后的写法:Sample two1 2 3 4 5 6 7 /** 本程序只适用于Windows系统,测试平台:* Windows XP,Microsoft Visual C++ 6.0 SP6*/8 9101112131415161718192021 #include <stdio.h>int main(){char ch1;char ch2;scanf("%c",&ch1);printf("ch1 = %d",ch1);fflush(stdin); /*清空缓冲区,也可以使用rewind(stdin);*/scanf("%c",&ch2);printf("ch2 = %d",ch2);return0;}上面的实例只适用于Windows系统,在Linux环境下上面两种写法都是不起作用的,所以还要换个函数。

C语言清空输入缓冲区的N种方法对比

C语言清空输入缓冲区的N种方法对比C语言中有几个基本输入函数://获取字符系列int fgetc(FILE *stream);int getc(FILE *stream);int getchar(void);//获取行系列char *fgets(char * restrict s, int n, FILE * restrict stream);资料个人收集整理,勿做商业用途char *gets(char *s);//可能导致溢出,用fgets代替之。

//格式化输入系列int fscanf(FILE * restrict stream, constchar* restrict format, …);资料个人收集整理,勿做商业用途int scanf(constchar* restrict format, …);int sscanf(constchar * restrict str, constchar* restrict format, …);资料个人收集整理,勿做商业用途这里仅讨论输入函数在标准输入(stdin)情况下的使用。

纵观上述各输入函数,获取字符系列的的前三个函数fgetc、getc、getchar。

以getchar为例,将在stdin缓冲区为空时,等待输入,直到回车换行时函数返回。

若stdin缓冲区不为空,getchar直接返回。

getchar返回时从缓冲区中取出一个字符,并将其转换为int,返回此int值。

资料个人收集整理,勿做商业用途MINGW 4.4.3中FILE结构体源码:typedefstruct _iobuf{char* _ptr;//指向当前缓冲区读取位置int_cnt;//缓冲区中剩余数据长度char* _base;int_flag;int_file;int_charbuf;int_bufsiz;char* _tmpfname;} FILE;各编译器实现可能不一样,这里获取字符系列函数只用到_ptr和_cnt。

贪吃蛇C语言源代码

#include <stdio.h>#include <stdlib.h>#include <Windows.h>//windows编程头文件#include <time.h>#include <conio.h>//控制台输入输出头文件#ifndef __cplusplustypedef char bool;#define false 0#define true 1#endif//将光标移动到控制台的(x,y)坐标点处void gotoxy(int x, int y){COORD coord;coord.X = x;coord.Y = y;SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord); }#define SNAKESIZE 100//蛇的身体最大节数#define MAPWIDTH 78//宽度#define MAPHEIGHT 24//高度//食物的坐标struct {int x;int y;}food;//蛇的相关属性struct {int speed;//蛇移动的速度int len;//蛇的长度int x[SNAKESIZE];//组成蛇身的每一个小方块中x的坐标int y[SNAKESIZE];//组成蛇身的每一个小方块中y的坐标}snake;//绘制游戏边框void drawMap();//随机生成食物void createFood();//按键操作void keyDown();//蛇的状态bool snakeStatus();//从控制台移动光标void gotoxy(int x, int y);int key = 72;//表示蛇移动的方向,72为按下“↑”所代表的数字//用来判断蛇是否吃掉了食物,这一步很重要,涉及到是否会有蛇身移动的效果以及蛇身增长的效果int changeFlag = 0;int sorce = 0;//记录玩家的得分int i;void drawMap(){//打印上下边框for (i = 0; i <= MAPWIDTH; i += 2)//i+=2是因为横向占用的是两个位置{//将光标移动依次到(i,0)处打印上边框gotoxy(i, 0);printf("■");//将光标移动依次到(i,MAPHEIGHT)处打印下边框gotoxy(i, MAPHEIGHT);printf("■");}//打印左右边框for (i = 1; i < MAPHEIGHT; i++){//将光标移动依次到(0,i)处打印左边框gotoxy(0, i);printf("■");//将光标移动依次到(MAPWIDTH, i)处打印左边框gotoxy(MAPWIDTH, i);printf("■");}//随机生成初试食物while (1){srand((unsigned int)time(NULL));food.x = rand() % (MAPWIDTH - 4) + 2;food.y = rand() % (MAPHEIGHT - 2) + 1;//生成的食物横坐标的奇偶必须和初试时蛇头所在坐标的奇偶一致,因为一个字符占两个字节位置,若不一致//会导致吃食物的时候只吃到一半if (food.x % 2 == 0)break;}//将光标移到食物的坐标处打印食物gotoxy(food.x, food.y);printf("*");//初始化蛇的属性snake.len = 3;snake.speed = 200;//在屏幕中间生成蛇头snake.x[0] = MAPWIDTH / 2 + 1;//x坐标为偶数snake.y[0] = MAPHEIGHT / 2;//打印蛇头gotoxy(snake.x[0], snake.y[0]);printf("■");//生成初试的蛇身for (i = 1; i < snake.len; i++){//蛇身的打印,纵坐标不变,横坐标为上一节蛇身的坐标值+2snake.x[i] = snake.x[i - 1] + 2;snake.y[i] = snake.y[i - 1];gotoxy(snake.x[i], snake.y[i]);printf("■");}//打印完蛇身后将光标移到屏幕最上方,避免光标在蛇身处一直闪烁gotoxy(MAPWIDTH - 2, 0);return;}void keyDown(){int pre_key = key;//记录前一个按键的方向if (_kbhit())//如果用户按下了键盘中的某个键{fflush(stdin);//清空缓冲区的字符//getch()读取方向键的时候,会返回两次,第一次调用返回0或者224,第二次调用返回的才是实际值key = _getch();//第一次调用返回的不是实际值key = _getch();//第二次调用返回实际值}/**蛇移动时候先擦去蛇尾的一节*changeFlag为0表明此时没有吃到食物,因此每走一步就要擦除掉蛇尾,以此营造一个移动的效果*为1表明吃到了食物,就不需要擦除蛇尾,以此营造一个蛇身增长的效果*/if (changeFlag == 0){gotoxy(snake.x[snake.len - 1], snake.y[snake.len - 1]);printf(" ");//在蛇尾处输出空格即擦去蛇尾}//将蛇的每一节依次向前移动一节(蛇头除外)for (i = snake.len - 1; i > 0; i--){snake.x[i] = snake.x[i - 1];snake.y[i] = snake.y[i - 1];}//蛇当前移动的方向不能和前一次的方向相反,比如蛇往左走的时候不能直接按右键往右走//如果当前移动方向和前一次方向相反的话,把当前移动的方向改为前一次的方向if (pre_key == 72 && key == 80)key = 72;if (pre_key == 80 && key == 72)key = 80;if (pre_key == 75 && key == 77)key = 75;if (pre_key == 77 && key == 75)key = 77;/***控制台按键所代表的数字*“↑”:72*“↓”:80*“←”:75*“→”:77*///判断蛇头应该往哪个方向移动switch (key){case 75:snake.x[0] -= 2;//往左break;case 77:snake.x[0] += 2;//往右break;case 72:snake.y[0]--;//往上break;case 80:snake.y[0]++;//往下break;}//打印出蛇头gotoxy(snake.x[0], snake.y[0]);printf("■");gotoxy(MAPWIDTH - 2, 0);//由于目前没有吃到食物,changFlag值为0changeFlag = 0;return;}void createFood(){if (snake.x[0] == food.x && snake.y[0] == food.y)//蛇头碰到食物{//蛇头碰到食物即为要吃掉这个食物了,因此需要再次生成一个食物while (1){int flag = 1;srand((unsigned int)time(NULL));food.x = rand() % (MAPWIDTH - 4) + 2;food.y = rand() % (MAPHEIGHT - 2) + 1;//随机生成的食物不能在蛇的身体上for (i = 0; i < snake.len; i++){if (snake.x[i] == food.x && snake.y[i] == food.y){flag = 0;break;}}//随机生成的食物不能横坐标为奇数,也不能在蛇身,否则重新生成if (flag && food.x % 2 == 0)break;}//绘制食物gotoxy(food.x, food.y);printf("*");snake.len++;//吃到食物,蛇身长度加1sorce += 10;//每个食物得10分snake.speed -= 5;//随着吃的食物越来越多,速度会越来越快changeFlag = 1;//很重要,因为吃到了食物,就不用再擦除蛇尾的那一节,以此来造成蛇身体增长的效果}return;}bool snakeStatus(){//蛇头碰到上下边界,游戏结束if (snake.y[0] == 0 || snake.y[0] == MAPHEIGHT)return false;//蛇头碰到左右边界,游戏结束if (snake.x[0] == 0 || snake.x[0] == MAPWIDTH)return false;//蛇头碰到蛇身,游戏结束for (i = 1; i < snake.len; i++){if (snake.x[i] == snake.x[0] && snake.y[i] == snake.y[0])return false;}return true;}int main(){drawMap();while (1){keyDown();if (!snakeStatus())break;createFood();Sleep(snake.speed);}gotoxy(MAPWIDTH / 2, MAPHEIGHT / 2);printf("Game Over!\n");gotoxy(MAPWIDTH / 2, MAPHEIGHT / 2 + 1);printf("本次游戏得分为:%d\n", sorce);Sleep(5000);return 0;}。

C语言fflush()函数:清空文件缓冲区(或标准输入输出缓冲区)

头文件:#include<stdio.h>
fflush()不是标准库文件,经笔者测试,VC6.0完美支持,GCC(GCC4.6.2)不支持。
fflush()用于清空文件缓冲区,如果文件是以写的方式打开的,则把缓冲区内容写入文件。其原型为:
int fflush(FILE* stream);
【参数】stream为文件指针。
a = 123, c = a
(代码二)
#include <stdio.h>
#include <stdlib.h>
int main(){
int a;
char c;
scanf("%d", &a);
fflush(stdin);
c = getchar();
printf("a = %d, c = %c \n", a, c);
return 0;
}
运行结果:
123abc↙
xyz↙
a = 123, c = x
对比上面的代码,代码一没有清空输入缓冲区,回车时,将123赋值给a,缓冲区剩下abc,接着执行getchar(),发现缓冲区有内容,就无需等待用户输入,直接读取了,将'a'赋给c。代码二执行到fflush(),清空缓冲区,getchar()发现缓冲区没有内容,需要等待用户输入,所以必须输入两次。
【返回值】成功返回0,失败返回EOF,错误代码存于errno中。指定的流没有缓冲区或者只读打开时也返回0值。
fflush()也可用于标准输入(stdin)和标准输出(tandard input的缩写,即标准输入,一般是指键盘;标准输入缓冲区即是用来暂存从键盘输入的内容的缓冲区。stdout是standard output的缩写,即标准输出,一般是指显示器;标准输出缓冲区即是用来暂存将要显示的内容的缓冲区。

c语言中getch的用法

c语言中getch的用法C语言中getch的用法介绍getch是C语言中的一个函数,其主要作用是从键盘输入一个字符,且该字符不会在屏幕上显示出来。

因此,getch可以用于实现一些需要隐藏输入内容的场景。

语法getch函数的语法如下:int getch(void);参数说明getch函数没有任何参数。

返回值说明getch函数返回一个整数值,表示从键盘输入的字符对应的ASCII码值。

注意事项1. 在使用getch函数前需要包含头文件conio.h。

2. getch函数在不同操作系统和编译器中可能存在差异,因此建议在使用时查看相关文档或参考资料。

3. 在使用getch函数时需要注意缓冲区问题,即在调用该函数后如果没有将缓冲区清空,则后续从键盘输入的字符可能会被误认为是之前调用getch函数时输入的字符。

因此,在使用完getch函数后建议调用fflush(stdin)或者while(getchar()!='\n')等方法清空缓冲区。

示例代码下面是一个简单的示例代码,演示了如何使用getch函数从键盘读取一个字符并输出其ASCII码值:#include <stdio.h>#include <conio.h>int main(){char ch;printf("Please input a character:\n");ch = getch();printf("The ASCII code of the character is %d.\n", ch);return 0;}输出结果:Please input a character:aThe ASCII code of the character is 97.应用场景1. 密码输入在实现登录等功能时,为了保护用户的隐私,通常需要隐藏用户输入的密码。

可以使用getch函数读取用户输入的字符,并将其替换为'*'等符号。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

fflush 清空缓冲区.txt2008太不正常了,一切都不正常!在这个关键时刻,中国男足挺身而出,向全世界证明:中国男足还是正常的!fflush详解1、为什么 fflush(stdin) 是错的首先请看以下程序:#include <stdio.h>int main( void ){int i;for (;;){fputs("Please input an integer: ", stdout);scanf("%d", &i);printf("%d\n", i);}return 0;}这个程序首先会提示用户输入一个整数,然后等待用户输入,如果用户输入的是整数,程序会输出刚才输入的整数,并且再次提示用户输入一个整数,然后等待用户输入。

但是一旦用户输入的不是整数(如小数或者字母),假设 scanf 函数最后一次得到的整数是 2 ,那么程序会不停地输出“Please input an integer: 2”。

这是因为 scanf("%d", &i); 只能接受整数,如果用户输入了字母,则这个字母会遗留在“输入缓冲区”中。

因为缓冲中有数据,故而 scanf 函数不会等待用户输入,直接就去缓冲中读取,可是缓冲中的却是字母,这个字母再次被遗留在缓冲中,如此反复,从而导致不停地输出“Please input an integer: 2”。

也许有人会说:“居然这样,那么在 scanf 函数后面加上‘fflush(stdin);’,把输入缓冲清空掉不就行了?”然而这是错的!C和C++的标准里从来没有定义过 fflush(stdin)。

也许有人会说:“可是我用 fflush(stdin) 解决了这个问题,你怎么能说是错的呢?”的确,某些编译器(如VC6)支持用 fflush(stdin) 来清空输入缓冲,但是并非所有编译器都要支持这个功能(linux 下的 gcc 就不支持),因为标准中根本没有定义 fflush(stdin)。

MSDN 文档里也清楚地写着fflush on input stream is an extension to the C standard(fflush 操作输入流是对 C 标准的扩充)。

当然,如果你毫不在乎程序的移植性,用 fflush(stdin) 也没什么大问题。

以下是 C99 对 fflush 函数的定义:int fflush(FILE *stream);如果 stream 指向输出流或者更新流(update stream),并且这个更新流最近执行的操作不是输入,那么 fflush 函数将把这个流中任何待写数据传送至宿主环境(host environment)写入文件。

否则,它的行为是未定义的。

原文如下:int fflush(FILE *stream);If stream points to an output stream or an update stream in whichthe most recent operation was not input, the fflush function causesany unwritten data for that stream to be delivered to the host environmentto be written to the file; otherwise, the behavior is undefined.其中,宿主环境可以理解为操作系统或内核等。

由此可知,如果 stream 指向输入流(如 stdin),那么 fflush 函数的行为是不确定的。

故而使用 fflush(stdin) 是不正确的,至少是移植性不好的。

2、清空输入缓冲区的方法虽然不可以用 fflush(stdin),但是我们可以自己写代码来清空输入缓冲区。

只需要在scanf 函数后面加上几句简单的代码就可以了。

/* C 版本 */#include <stdio.h>int main( void ){int i, c;for ( ; ; ){fputs("Please input an integer: ", stdout);scanf("%d", &i);if ( feof(stdin) || ferror(stdin) ){ /* 如果用户输入文件结束标志(或文件已被读完), *//* 或者发生读写错误,则退出循环 *//* do something */break;}/* 没有发生错误,清空输入流。

*//* 通过 while 循环把输入流中的余留数据“吃”掉 */while ( (c = getchar()) != '\n' && c != EOF ) ;/* 使用 scanf("%*[^\n]"); 也可以清空输入流, *//* 不过会残留 \n 字符。

*/printf("%d\n", i);}return 0;}/* C++ 版本 */#include <iostream>#include <limits> // 为了使用numeric_limitsusing std::cout;using std::endl;using std::cin;using std::numeric_limits;using std::streamsize;int main(){int value;for ( ; ; ){cout << "Enter an integer: ";cin >> value;if ( cin.eof() || cin.bad() ){ // 如果用户输入文件结束标志(或文件已被读完),// 或者发生读写错误,则退出循环// do somethingbreak;}// 读到非法字符后,输入流将处于出错状态,// 为了继续获取输入,首先要调用 clear 函数// 来清除输入流的错误标记,然后才能调用// ignore 函数来清除输入流中的数据。

cin.clear();// numeric_limits<streamsize>::max() 返回输入缓冲的大小。

// ignore 函数在此将把输入流中的数据清空。

// 这两个函数的具体用法请读者自行查询。

cin.ignore( numeric_limits<streamsize>::max(), '\n' );cout << value << '\n';}return 0;}标准I / O提供缓存的目的是尽可能减少使用read和write调用的数量。

它也对每个I / O流自动地进行缓存管理,避免了应用程序需要考虑这一点所带来的麻烦。

不幸的是,标准I / O库令人最感迷惑的也是它的缓存。

不同类型缓存往往使人在进行I/O操作时不知所措。

标准I / O提供了三种类型的缓存:全缓存、行缓存、无缓存。

说的最清楚的要数Stevens的《UNIX环境高级编程》了,以下摘自Stevens的《UNIX 环境高级编程》第五章://******************标准I / O提供了三种类型的缓存:(1) 全缓存。

在这种情况下,当填满标准I / O缓存后才进行实际I / O操作。

对于驻在磁盘上的文件通常是由标准I / O库实施全缓存的。

在一个流上执行第一次I / O操作时,相关标准I / O函数通常调用m a l l o c(见7 . 8节)获得需使用的缓存。

术语刷新( f l u s h)说明标准I / O缓存的写操作。

缓存可由标准I / O例程自动地刷新(例如当填满一个缓存时),或者可以调用函数ff l u s h刷新一个流。

值得引起注意的是在U N I X环境中,刷新有两种意思。

在标准I / O库方面,刷新意味着将缓存中的内容写到磁盘上(该缓存可以只是局部填写的)。

在终端驱动程序方面(例如在第11章中所述的t c f l u s h函数),刷新表示丢弃已存在缓存中的数据。

(2) 行缓存。

在这种情况下,当在输入和输出中遇到新行符时,标准I / O库执行I / O操作。

这允许我们一次输出一个字符(用标准I/O fputc函数),但只有在写了一行之后才进行实际I / O操作。

当流涉及一个终端时(例如标准输入和标准输出),典型地使用行缓存。

对于行缓存有两个限制。

第一个是:因为标准I / O库用来收集每一行的缓存的长度是固定的,所以只要填满了缓存,那么即使还没有写一个新行符,也进行I / O操作。

第二个是:任何时候只要通过标准输入输出库要求从( a )一个不带缓存的流,或者( b )一个行缓存的流(它预先要求从内核得到数据)得到输入数据,那么就会造成刷新所有行缓存输出流。

在( b )中带了一个在括号中的说明的理由是,所需的数据可能已在该缓存中,它并不要求内核在需要该数据时才进行该操作。

很明显,从不带缓存的一个流中进行输入( ( a )项)要求当时从内核得到数据。

(3) 不带缓存。

标准I / O库不对字符进行缓存。

如果用标准I / O函数写若干字符到不带缓存的流中,则相当于用w r i t e系统调用函数将这些字符写至相关联的打开文件上。

标准出错流s t d e r r通常是不带缓存的,这就使得出错信息可以尽快显示出来,而不管它们是否含有一个新行字符。

ANSI C要求下列缓存特征:(1) 当且仅当标准输入和标准输出并不涉及交互作用设备时,它们才是全缓存的。

(2) 标准出错决不会是全缓存的。

但是,这并没有告诉我们如果标准输入和输出涉及交互作用设备时,它们是不带缓存的还是行缓存的,以及标准输出是不带缓存的,还是行缓存的。

S V R 4和4 . 3 + B S D的系统默认使用下列类型的缓存:? 标准出错是不带缓存的。

? 如若是涉及终端设备的其他流,则它们是行缓存的;否则是全缓存的。

//*****************************我们经常要用到标准输入和输出,而ANSI C对stdin、stdout和stderr的缓存特征没有强行的规定,以至于不同的系统可能有不同的stdin、stdout和stderr的缓存特征。

目前主要的缓存特征是:stdin和stdout是行缓存;而stderr是无缓存的。

相关文档
最新文档