C++ >>和<<读写文本文件
生活随笔
收集整理的這篇文章主要介紹了
C++ >>和<<读写文本文件
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
執行此程序之前,必須在和該程序源文件同目錄中手動創建一個 in.txt 文件,假設其內部存儲的字符串為:
10 20 30 40 #include <iostream> #include <fstream> using namespace std; int main() {int x,sum=0;ifstream srcFile("in.txt", ios::in); //以文本模式打開in.txt備讀if (!srcFile) { //打開失敗cout << "error opening source file." << endl;return 0;}ofstream destFile("out.txt", ios::out); //以文本模式打開out.txt備寫if (!destFile) {srcFile.close(); //程序結束前不能忘記關閉以前打開過的文件cout << "error opening destination file." << endl;return 0;}//可以像用cin那樣用ifstream對象while (srcFile >> x) { //讀數據sum += x;//可以像 cout 那樣使用 ofstream 對象cout<<"x="<<x<<endl;destFile << x << " "; //寫數據}cout << "sum:" << sum << endl;destFile.close();srcFile.close();return 0; } g++ -g main.cpp -o main./main總結
以上是生活随笔為你收集整理的C++ >>和<<读写文本文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++打开的文件一定要用close()方
- 下一篇: 目前工作常用脚本