Advertisement
gha890826

C++ File I/O practice

Apr 30th, 2019
207
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.86 KB | None | 0 0
  1. // ConsoleApplication1.cpp : 定義主控台應用程式的進入點。
  2. //
  3.  
  4. #include "stdafx.h"
  5. #include<iostream>
  6. #include<fstream>
  7. #include<string>
  8. using namespace std;
  9.  
  10. void main()
  11. {
  12.     fstream file1;
  13.     string infile1;
  14.     file1.open("c:\\test.txt", ios_base::in);
  15.     if (!file1)
  16.         cout << "檔案開啟失敗\n";
  17.     else
  18.     {
  19.         int counter=0;
  20.         while (!file1.eof())   //若到達檔案結尾則”file>>str”將 傳回0, 跳出while回圈
  21.  
  22.         {
  23.             char str;
  24.             file1.get(str);
  25.             if (!file1.good())  //如果讀取的字元是不正常的則跳出迴圈
  26.                 break;
  27.             if (str == '3')
  28.                 counter++;
  29.             infile1 += str;
  30.         }
  31.         cout <<"讀取到:\n"<< infile1 << endl << endl;
  32.         fstream file2;
  33.         file2.open("c:\\test2.txt", ios_base::out);
  34.         if (file2)
  35.         {
  36.             file2 << infile1;
  37.         }
  38.         cout << "複製完畢\n共有 "<<counter<<" 個3\n";
  39.        
  40.     }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement