接續剛才寫的開啟檔案和寫入檔案,這次換寫開啟檔案讀取檔案的程式,依然很簡單,只是稍有差別。
程式碼大部分一致。
/**
Theme: Open File and Read
Compiler: Dev C++ 4.9.9.2
Date: 100/05/31
Author: ShengWen
Blog: https://cg2010studio.wordpress.com/
*/
#include<iostream>
#include<fstream>
using namespace std;
int main(){
char filename[]="xxx.txt";
fstream fp;
char line[128];
fp.open(filename, ios::in);//開啟檔案
if(!fp){//如果開啟檔案失敗,fp為0;成功,fp為非0
cout<<"Fail to open file: "<<filename<<endl;
}
cout<<"File Descriptor: "<<fp<<endl;
while(fp.getline(line, sizeof(line), '\n')){
cout<<line<<endl;
}
fp.close();//關閉檔案
system("pause");
return EXIT_SUCCESS;
}
我使用getline()來讀取字串,以‘\n’ (換行字元)為分隔,我也可以使用‘ ‘(空白鍵)來作為分隔字元,接著就可以依據需求來處理字串。
Comments on: "[C++] 開啟檔案和讀取檔案 (Open File and Read File)" (4)
假如TXT檔 裡都是數字 要如何拿來做運算
讚讚
首先你要讀取所有文字,接著以空格字元分開每個數字,最後每個數字字串轉成數字來運算,以上。
讚讚
如何將字串轉成數字 感謝
讚Liked by 1 person
假如我的txt是這樣
123
484
545
2654
4898
要如何把 484 存到一個變數
讚讚