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

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

C++文件讀寫代碼分享

2020-01-26 15:03:12
字體:
來源:轉載
供稿:網友

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

算法提示:

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

(1)實現源代碼

#include <iostream>#include <fstream>#include <string>#include <sstream> using namespace std; int coutFile(char * filename,char * outfilename){  ifstream filein;  filein.open(filename,ios_base::in);  ofstream fileout;  fileout.open(outfilename,ios_base::out);  string strtemp;  int count=0;  while(getline(filein,strtemp))  {    count++;    cout<<strtemp<<endl;    fileout<<count<<" "<<strtemp<<endl;  }  filein.close();  fileout.close();  return count;}  void main(){  cout<<coutFile("c://data.txt","c://data1.txt")<<endl;}

再來一個示例:

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

#include <fstream>#include <iostream>using namespace std;  int main (){     char data[100];   // open a file in write mode.  ofstream outfile;  outfile.open("afile.dat");   cout << "Writing to the file" << endl;  cout << "Enter your name: ";  cin.getline(data, 100);   // write inputted data into the file.  outfile << data << endl;   cout << "Enter your age: ";  cin >> data;  cin.ignore();     // again write inputted data into the file.  outfile << data << endl;   // close the opened file.  outfile.close();   // open a file in read mode.  ifstream infile;  infile.open("afile.dat");    cout << "Reading from the file" << endl;  infile >> data;   // write the data at the screen.  cout << data << endl;     // again read the data from the file and display it.  infile >> data;  cout << data << endl;   // close the opened file.  infile.close();   return 0;}

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

$./a.outWriting to the fileEnter your name: ZaraEnter your age: 9Reading from the fileZara9

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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 中宁县| 崇信县| 黑河市| 铜梁县| 屏东市| 嘉义市| 成武县| 赞皇县| 江门市| 青川县| 石柱| 枣强县| 武穴市| 纳雍县| 南木林县| 东光县| 南康市| 新竹县| 香格里拉县| 比如县| 虎林市| 墨玉县| 霍邱县| 慈利县| 宝坻区| 正阳县| 博罗县| 科技| 通化县| 大埔县| 望江县| 湖南省| 文昌市| 随州市| 阳西县| 巨鹿县| 万载县| 碌曲县| 秦皇岛市| 珠海市| 昌宁县|