Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using C++ splitting a section string which is in "[General Setting]" format

Tags:

c++

I am new to C++, i want to read ini file which has section and key - value pair. Depending on the section, i want to read the value for corresponding key. Primarily, i want to read the section which is enclosed in square brackets. Please help. Thank you.

like image 404
user1409360 Avatar asked Nov 18 '25 03:11

user1409360


1 Answers

For real INI file parsing, I highly suggest the iniparser library. It is excellently documented and easy to use in both C and C++ programs.

If you are only interested in parsing strings of the form [Section name], you could do the following: Find first '[' and last ']' for the string and mark the positions. If both characters have been found, take the section name to be substring between the positions you identified.

Assuming you are using an std::string, you can do the following:

std::string myString = " [Section name] ";

std::size_t start = myString.find_first_of( '[' );
std::size_t end   = myString.find_last_of( ']' );

std::string sectionName;
if( start != std::string::npos && end != std::string::npos )
{
  sectionName = myString.substr(start + 1, end - 1);
}

std::cout << sectionName << std::endl;
like image 140
Gnosophilon Avatar answered Nov 19 '25 17:11

Gnosophilon