哇,今天又重新用C++來寫了一些代碼發現自己竟然在類的使用和文件讀取和保存上面特別頭疼,於是,各種問度娘+各種翻看之前的代碼。不禁感嘆,自己的代碼還是寫的太少了,對這些一點都不熟悉。於是,今晚!一定!要!好好!總結!提升!
- 首先,類的使用方式:
1 Walking *a = new Walking();// a是該類型的指針 2 a->Procesee; 3 Walking a;//a是該類型的一個對象 4 a.Process;
- #define的相關用法:
//簡單的 define 定義 #define PI (3.1415926) //無需等號、分號,需要括號 //帶參數的宏定義 #define MAX(a,b) ((a)>(b)?(a):(b)) //定義宏和取消宏 #define #undef //使用宏進行條件編譯,莫扎特的框架里有用到 #ifdef (#else) #endif //防止重復編譯格式,QT里會自動生成 #ifndef _HELLO_H_ #define _HELLO_H ``` //文件內容 ··· #endif
- 文件路徑的問題
//最好是英文路徑名 //這個寫法是錯誤的!一直用MATLAB,這樣寫沒有問題,突然換到C里面,這樣寫是不對的 fout1 = fopen("E:\football\gait\data\L\Hip_Yaw.txt","w"); //要用雙斜杠 fout1 = fopen("E:\\football\\gait\\data\\L\\Hip_Yaw.txt","w");
- 文件讀寫的方式
//內容來自:https://www.cnblogs.com/codingmengmeng/p/5545042.html //第一種方式:ofstream ifstream fstream //打開文件 //函數open() public member function void open ( const char * filename, ios_base::openmode mode = ios_base::in | ios_base::out ); /* 參數:filename 操作文件名 mode 打開文件的方式 */
//函數close()
//負責將緩存中的數據排放出來並關閉文件,這個函數一旦被調用,原先的流對象就可以被用來打開其他的文件
例子:
1 ifstream ifile1("E:\\football\\gait\\data\\trails\\L_x.txt",ios::in); 2 if(!ifile1) 3 cerr<<"error_O_L"<<endl; 4 string lineword; 5 int j = 0; 6 while (ifile1 >> lineword) 7 { 8 sscanf(lineword.c_str(), "%lf", &x_L[j]);//讀取到x_L數組里面 9 printf("%lf\n",x_L[j]); 10 j++; } 11 ifile1.close();
#include "iostream" #include<fstream> //頭文件!! using namespace std; void main() { fstream f("d:\\try.txt", ios::out);//供寫使用,文件不存在則創建,存在則清空原內容 f << 1234 << ' ' << 3.14 << 'A' << "How are you"; //寫入數據 f.close();//關閉文件以使其重新變為可訪問,函數一旦調用,原先的流對象就可以被用來打開其它的文件 f.open("d:\\try.txt", ios::in);//打開文件,供讀 int i; double d; char c; char s[20]; f >> i >> d >> c; //讀取數據 f.getline(s, 20); cout << i << endl; //顯示各數據 cout << d << endl; cout << c << endl; cout << s << endl; f.close(); }
//第二種方法 FILE* fout1 = NULL; fout1 = fopen("E:\\football\\gait\\data\\L\\Hip_Yaw.txt","a+"); if(!fout1) cerr<<"error_S_L"<<endl; fprintf(fout1,"%lf\n",out[0]*180/PI); fclose(fout1);