自己沒有用C++做過開發,一直是用C#,Java這類OO語言或者JS,shell之類的指令碼語言。所以偶爾想寫一些C++的代碼,還挺困難。
1.如何訪問一個二維數組
1 //the arry that we want to access
2 char Country[255][60] = {"China", "England", "USA"};
3
4 //method 1
5 int i=0;
6 while(*Country[i] != NULL) {
7 std::cout << Country[i] << std::endl;
8 i++;
9 }
10
11 //method 2
12 int i=0
13 for(i=0;i<255;i++)
14 {
15 char* country = pArr->Country[i];
16 cout<<country<<endl;
17 }
2.函數指標的聲明與使用
1 //這裡定義fp為CReverseIP類型內的一個函數指標類型
2 typedef BOOL (CReverseIP::*fp)(const char* inputIP, IPInfo *ipInfo);
3
4 //在CReverseIP中聲明一個fp類型變數
5 class CReverseIP
6 {
7 /*some other stuff*/
8 public:
9 fp fParse;
10 /*some other stuff*/
11 }
12
13 //賦值
14 revIPTool->fParse = &CReverseIP::GetIPLocation_Old;
15
16 //使用
17 retvalue = (this->*fParse)(strLine.c_str(), ipInfo);
3.檔案讀寫(下面這段範例程式碼中讀寫具在)
1 BOOL CReverseIP::ParseIPFileToFile(string srcFile, string desFile)
2 {
3 ifstream streamIn(srcFile.c_str());
4 if(streamIn.fail())
5 {
6 cout<<srcFile<<" could not be opened."<<endl;
7 return FALSE;
8 }
9 fstream desStream;
10 desStream.open(desFile.c_str(),ios::in);
11 if(desStream)
12 {
13 cout<<desFile<<" already exists, overwrite?(Y/N)"<<endl;
14 desStream.close();
15 char c;
16 //c = getchar();
17 cin>>c;
18 switch(c)
19 {
20 case 'Y':
21 break;
22 case 'N':
23 return FALSE;
24 default:
25 break;
26 }
27 }
28
29 ofstream streamOut(desFile.c_str(), ios::out);
30 streamOut<<"ip\tcountry\tprovince\tcity"<<endl;
31 string strLine;
32 IPInfo* ipInfo = new IPInfo();
33 BOOL retvalue = FALSE;
34 while(getline(streamIn, strLine))
35 {
36 retvalue = (this->*fParse)(strLine.c_str(), ipInfo);
37 if(retvalue==TRUE && ipInfo!=NULL)
38 {
39 streamOut<<ipInfo->ip<<"\t"<<ipInfo->country<<"\t"<<ipInfo->province<<"\t"<<ipInfo->city<<endl;
40 }
41 else
42 {
43 continue;
44 }
45 }
46 streamIn.close();
47 streamOut.close();
48 delete ipInfo;
49 return TRUE;
50 }