文件輸入輸出
1.輸入輸出重定向
freopen("input.txt","r",stdin); //該語句使得所有讀鍵盤輸入的函數都從文件input.txt讀入,例如scanf。 freopen("output.txt","w",stdout); //該語句使得所有輸出到屏幕的函數都輸出到文件output.txt,例如printf。
2.fopen
#include<cstdio> #define INF100000000 int main() { FILE *fin,*fout;//文件指針 fin = fopen("data.in","rb"); fout = fopen("data.out","wb"); int x,n=0,min=INF,max=-INF,s=0; while(fscanf(fin,"%d",&x)==1) { s+=x; if(x<min)min=x; if(x>max)max=x; n++; } fprintf(fout,"%d %d %.3f\n",min,max,(double)s/n); fclose(fin); fclose(fout); return 0; }
3.字符數組
fgetc(fin)//從打開的文件fin中讀取一個字符,在標准輸入中等價於getchar(); fgets(buf,maxn,fin);//讀取完整的一行放在字符數組buf里,這個函數讀取不超過 //maxn-1個字符,然后再末尾添上結束符\0,因此不會出現越 // 界,讀到換行符工作停止,沒有讀到字符時返回NULL
標准輸入輸出
1.cin/cout
#include<iostream> int main(){ int a; cin>>a; //(1)cin語句把空格和換行符作為分隔符,不輸入給變量 cout<<a; return 0; }
2.scanf/printf
scanf("格式控制字符串",輸出列表); printf("格式控制字符串“,地址列表);
3.字符串的輸入輸出
字符數組:
(1)
#include<cstdio> #include<cstring> int main(){ char s[20]; scanf("%s",s);//s前不需要加地址,因為數組名本身就指向數組首元素 2.遇空格結束 printf("%s",s); return 0; }
(2)
getchar(); //從標准輸入中讀取下一個字符,返回類型為int型,為用戶輸入的ASCII碼 putchar(); //向終端輸出一個字符
(3)
puts(s);//輸出字符串s和一個換行符
gets(s);//讀取一行字符存入s //由於沒有指明讀取的最大字符數,因而存在緩沖區漏洞,在C11標准中,該函數已被刪除.
(4)
#include <iostream> using namespace std; int main () { char s[20]; cin.getline(s,5,'\n'); //讀取一行,5是最大的讀取的字符數(包含結束符'\0'),\n是分隔符,可以省略,即cin.getline(s,5); cout<<m<<endl; }
(5)
sprintf(s,"%d",N)1.將整數N轉化成字符串s. sscanf(s,"%d",&N)2.字符串s轉換成數字N.