#include
#include
#include < string >
using namespace std;
void OutPutAnEmptyLine()//輸出空行
{
cout<< "
" ;
}
//讀取方式: 逐詞讀取, 詞之間用空格區(qū)分
void ReadDataFromFileWBW()
{
cout<<"逐詞讀取, 詞之間用空格區(qū)分"<
string s;
while ( fin >> s )
{
cout << "Read from file: " << s << endl;
}
}
//讀取方式: 逐行讀取, 將行讀入字符數(shù)組, 行之間用回車換行區(qū)分
void ReadDataFromFileLBLIntoCharArray()
{
cout<<"逐行讀取, 將行讀入字符數(shù)組, 行之間用回車換行區(qū)分"<
const int LINE_LENGTH = 100 ;
char str[LINE_LENGTH];
while ( fin.getline(str,LINE_LENGTH) )
{
cout << "Read from file: " << str << endl;
}
}
//讀取方式: 逐行讀取, 將行讀入字符串, 行之間用回車換行區(qū)分
//相比較上種方法,該種方法比較靈活,推薦使用
void ReadDataFromFileLBLIntoString()
{
cout<<"逐行讀取, 將行讀入字符串, 行之間用回車換行區(qū)分"<
string s;
while ( getline(fin,s) )
{
cout << "Read from file: " << s << endl;
}
}
//帶錯誤檢測的讀取方式
void ReadDataWithErrChecking()
{
string filename = "dataFUNNY.txt" ;
ifstream fin( filename.c_str());
if ( !fin )
{
cout << "Error opening " << filename << " for input" << endl;
exit(- 1 );
}
}
int main()
{
ReadDataFromFileWBW(); //逐詞讀入字符串
OutPutAnEmptyLine(); //輸出空行
ReadDataFromFileLBLIntoCharArray(); //逐詞讀入字符數(shù)組
OutPutAnEmptyLine(); //輸出空行
ReadDataFromFileLBLIntoString(); //逐詞讀入字符串
OutPutAnEmptyLine(); //輸出空行
ReadDataWithErrChecking(); //帶檢測的讀取
return 0 ;
}