欧美大屁股bbbbxxxx,狼人大香伊蕉国产www亚洲,男ji大巴进入女人的视频小说,男人把ji大巴放进女人免费视频,免费情侣作爱视频

歡迎來(lái)到入門教程網(wǎng)!

C語(yǔ)言

當(dāng)前位置:主頁(yè) > 軟件編程 > C語(yǔ)言 >

C++文件讀寫代碼分享

來(lái)源:本站原創(chuàng)|時(shí)間:2020-01-10|欄目:C語(yǔ)言|點(diǎn)擊: 次

編寫一個(gè)程序,統(tǒng)計(jì)data.txt文件的行數(shù),并將所有行前加上行號(hào)后寫到data1.txt文件中。

算法提示:

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

(1)實(shí)現(xiàn)源代碼

#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;
}

再來(lái)一個(gè)示例:

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

#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;
}

程序編譯執(zhí)行后輸出如下結(jié)果

$./a.out
Writing to the file
Enter your name: Zara
Enter your age: 9
Reading from the file
Zara
9

以上所述就是本文的全部?jī)?nèi)容了,希望大家能夠喜歡。

上一篇:C++雙向循環(huán)列表用法實(shí)例

欄    目:C語(yǔ)言

下一篇:C語(yǔ)言打印華氏-攝氏溫度對(duì)照表的方法

本文標(biāo)題:C++文件讀寫代碼分享

本文地址:http://mengdiqiu.com.cn/a1/Cyuyan/2989.html

網(wǎng)頁(yè)制作CMS教程網(wǎng)絡(luò)編程軟件編程腳本語(yǔ)言數(shù)據(jù)庫(kù)服務(wù)器

如果侵犯了您的權(quán)利,請(qǐng)與我們聯(lián)系,我們將在24小時(shí)內(nèi)進(jìn)行處理、任何非本站因素導(dǎo)致的法律后果,本站均不負(fù)任何責(zé)任。

聯(lián)系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網(wǎng) 版權(quán)所有