Re: [問題] linux C/C++ 讀設定檔

看板C_and_CPP作者 (我要加入劍道社!)時間15年前 (2010/12/25 02:23), 編輯推噓1(101)
留言2則, 2人參與, 最新討論串3/3 (看更多)
※ 引述《mself (mself)》之銘言: : 開發平台(Platform): (Ex: VC++, Gcc, Linux, ...) : Linux : 問題(Question): : 想請問如何用 C/C++ 讀取一個設定檔 : 餵入的資料(Input): : 設定檔是一個文字檔,內容是字串跟設定值,例如: : height 5 : width 10 : lenght 30 : ... : 程式碼(Code): (請善用置底文標色功能) : 我大概寫成如下, : 功能正常,但想問問看有沒有比較聰明漂亮的寫法~ 做法 1. map<string, int> conf; string key; int value; fin >> key >> value; while( fin.good() ){ conf[key] = value; fin >> key >> value; } int size = conf["height"] * conf["width"] * conf["length"]; 做法 2. boost::property_tree::ptree pt; boost::property_tree::read_info(fin, pt); int height = pt.get<int>("height"); int width = pt.get<int>("width"); int length = pt.get<int>("length"); property tree 的好處是他會幫你 parse 檔案 而且也支援不同的語法 (包括 xml、json、ini 等) 不過要另外裝 boost library 就是了 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 118.168.78.69

12/25 03:17, , 1F
好強!!
12/25 03:17, 1F

12/25 07:17, , 2F
作法1先find會比較好吧? 雖然讓它插入新key也沒差
12/25 07:17, 2F
文章代碼(AID): #1D5EKFGA (C_and_CPP)
文章代碼(AID): #1D5EKFGA (C_and_CPP)