C++點滴

來源:互聯網
上載者:User

自己沒有用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 }

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.