国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C++ > 正文

C++文件讀寫代碼分享

2020-05-23 14:18:59
字體:
來源:轉載
供稿:網友

本文給大家分享的是2個C++實現文件讀寫的代碼,都非常的簡單實用,有需要的小伙伴可以參考下。

編寫一個程序,統計data.txt文件的行數,并將所有行前加上行號后寫到data1.txt文件中。

算法提示:

行與行之間以回車符分隔,而getline()函數以回車符作為終止符。因此,可以采用getline()函數讀取每一行,再用一個變量i計算行數。

(1)實現源代碼

 

 
  1. #include <iostream> 
  2. #include <fstream> 
  3. #include <string> 
  4. #include <sstream> 
  5.  
  6. using namespace std; 
  7.  
  8. int coutFile(char * filename,char * outfilename) 
  9. ifstream filein; 
  10. filein.open(filename,ios_base::in); 
  11. ofstream fileout; 
  12. fileout.open(outfilename,ios_base::out); 
  13. string strtemp; 
  14. int count=0; 
  15. while(getline(filein,strtemp)) 
  16. count++; 
  17. cout<<strtemp<<endl; 
  18. fileout<<count<<" "<<strtemp<<endl; 
  19. filein.close(); 
  20. fileout.close(); 
  21. return count; 
  22.  
  23.  
  24. void main() 
  25. cout<<coutFile("c://data.txt","c://data1.txt")<<endl; 

再來一個示例:

下面的C++代碼將用戶輸入的信息寫入到afile.dat,然后再通過程序讀取出來輸出到屏幕

 

 
  1. #include <fstream> 
  2. #include <iostream> 
  3. using namespace std; 
  4.  
  5. int main () 
  6.  
  7. char data[100]; 
  8.  
  9. // open a file in write mode. 
  10. ofstream outfile; 
  11. outfile.open("afile.dat"); 
  12.  
  13. cout << "Writing to the file" << endl; 
  14. cout << "Enter your name: "
  15. cin.getline(data, 100); 
  16.  
  17. // write inputted data into the file. 
  18. outfile << data << endl; 
  19.  
  20. cout << "Enter your age: "
  21. cin >> data; 
  22. cin.ignore(); 
  23.  
  24. // again write inputted data into the file. 
  25. outfile << data << endl; 
  26.  
  27. // close the opened file. 
  28. outfile.close(); 
  29.  
  30. // open a file in read mode. 
  31. ifstream infile; 
  32. infile.open("afile.dat"); 
  33.  
  34. cout << "Reading from the file" << endl; 
  35. infile >> data; 
  36.  
  37. // write the data at the screen. 
  38. cout << data << endl; 
  39.  
  40. // again read the data from the file and display it. 
  41. infile >> data; 
  42. cout << data << endl; 
  43.  
  44. // close the opened file. 
  45. infile.close(); 
  46.  
  47. return 0; 

程序編譯執行后輸出如下結果

 

 
  1. $./a.out 
  2. Writing to the file 
  3. Enter your name: Zara 
  4. Enter your age: 9 
  5. Reading from the file 
  6. Zara 

以上所述就是本文的全部內容了,希望大家能夠喜歡。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 兴海县| 双鸭山市| 阳谷县| 东兴市| 酉阳| 江永县| 贵州省| 全椒县| 子洲县| 凌源市| 习水县| 府谷县| 昭觉县| 甘洛县| 沐川县| 封开县| 宁德市| 千阳县| 云阳县| 永泰县| 望都县| 西充县| 长岭县| 昭苏县| 巨野县| 车险| 德安县| 改则县| 皮山县| 仲巴县| 唐海县| 平顺县| 岳池县| 牟定县| 永年县| 藁城市| 清流县| 高唐县| 渑池县| 沙湾县| 乐都县|