有時候我們需要的數據被放在了文件裏,並且數據量比較大,我們也不想去複製的時候;或者我們爲了簡化調試程序的步驟;或者是我們的程序需要初始化,但是又不能讓用戶去輸入初始數據,我們就可以使用文件讀入的方法
首先要將數據文件和程序文件放在同一工作目錄下
第一種是C語言的方法
使用文件指針 FILE,配合fscanf來使用
在頭文件 stdio.h 裏
#include<stdio.h>
#include<stdlib.h>
int main()
{
int n,x;
printf("--C--\n");
FILE* f=fopen("file.txt","r");//創建文件指針 r代表讀文件
if(!f){
printf("file open error!\n");
exit(0);
}
fscanf(f,"%d",&n);//注意格式
printf("n=%d\n",n);
while(n--){
fscanf(f,"%d",&x);
printf("%d\n",x);
}
fclose(f);//不要忘記關閉文件
return 0;
}
第二種是C++的方法
創建輸入流ifstream對象,直接讀取
需要包含頭文件 fstream
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
int n,x;
cout<<"--C++--"<<endl;
ifstream myin("file.txt");//創建輸入流對象
if(!myin){
cout<<"file open error!"<<endl;
exit(0);
}
myin>>n;
cout<<"n="<<n<<endl;
while(n--){
myin>>x;
cout<<x<<endl;
}
myin.close();//不要忘記關閉
return 0;
}
二者都可以配合while(fscanf()!=EOF)或者while(**in>>x)來使用
當然還有往文件裏寫的操作,這裏就不說了,畢竟競賽還是讀文件的操作用的比較多