随手写个解析INI配置字符串的小例子 带测试
#include <iostream> #include <map> #include <string> #include "unittest.h" bool IniParser(std::string inputStr,std::map<std::string,std::string>& keyValueMap){ bool ret = false; size_t keyStart = 0; for(keyStart= 0 ;keyStart < inputStr.size();keyStart++){ if(inputStr[keyStart] == ' '){ continue; //去除空格 }else if( inputStr[keyStart] == ';' || inputStr[keyStart] == '#' || inputStr[keyStart] == '[' || inputStr[keyStart] == ']' || inputStr[keyStart] == '='){ return ret; // 各种意外开头 直接返回失败 }else{ break; } } size_t findPos = inputStr.find_first_of("=",keyStart); if(std::string::npos == findPos){ return ret;//没有找到"=" } std::string keyString = inputStr.substr(keyStart,findPos -keyStart); // std::cout << "keyString:" << keyString << std::endl; for(keyStart= findPos+1 ;keyStart < inputStr.size();keyStart++){ if(inputStr[keyStart] == ' '){ continue; //去除空格 }else{ break; } } std::string valueString = inputStr.substr(keyStart); //std::cout << "valueString:" << valueString << std::endl; keyValueMap.insert(std::pair<std::string,std::string>(keyString,valueString)); ret = true; return ret; } std::string testStr1 = "key=value"; std::string testStr2 = " key = value"; std::string testStr3 = "# key=value"; std::string testStr4 = "== key=value"; std::string testStr5 = "[ 23423key=value"; std::string testStr6 = "]324234key=value"; std::string testStr7 = ";key= = value"; std::string testStr8 = " key = = value"; int main(int argc, char *argv[]) { std::map<std::string,std::string> keyValueMap; EXCEPT_EQ( IniParser(testStr1,keyValueMap),true); EXCEPT_EQ( IniParser(testStr2,keyValueMap),true); EXCEPT_EQ( IniParser(testStr3,keyValueMap),false); EXCEPT_EQ( IniParser(testStr4,keyValueMap),false); EXCEPT_EQ( IniParser(testStr5,keyValueMap),false); EXCEPT_EQ( IniParser(testStr6,keyValueMap),false); EXCEPT_EQ( IniParser(testStr7,keyValueMap),false); EXCEPT_EQ( IniParser(testStr8,keyValueMap),true); PRINT_TEST_RESULT(); return 0; }
测试头文件
#ifndef UNITTEST_H #define UNITTEST_H #include <iostream> class MyTestClass { static size_t testCount_; static size_t testPass_; public: template<typename E,typename A> bool ExceptEqual(E e, A a) { testCount_++; if (e == a){ testPass_++; return true; } return false; } void PrintResult(){ std::cout << testPass_ << "/" << testCount_ << "\t" << "("<<(testPass_ * 100.0 / testCount_) << "%)" << " passed." << std::endl; } }; size_t MyTestClass::testCount_ = 0; size_t MyTestClass::testPass_ = 0; #define ERROR_PRINT(expect,actual) \ std::cerr << __FILE__ <<":"<< __LINE__ << "\r\nexpect: " << expect << " actual: " << actual << std::endl; #define EXCEPT_EQ(expect, actual) \ do{ \ MyTestClass TEST; \ if(!TEST.ExceptEqual(expect, actual)){ \ ERROR_PRINT(expect,actual) \ } \ }while(0) #define PRINT_TEST_RESULT() \ do{ \ MyTestClass TEST; \ TEST.PrintResult(); \ }while(0) #endif // UNITTEST_H