lundi 11 octobre 2021

C++ string delimiter exception

I'm working on a piece of code and encountered a small problem here. In an overall the problem is with a string delimiter and a splitting of a C++ std::string.

The string that I have is:

std::string nStr = 
R"(
"0000:ae:05.2:
Address: 0000:ae:05.2
Segment: 0x0000
")";

Normally the above is way larger and has many more data entries. The delimiter I have set is the ": " as it will be the most common delimiter I have in the data. What I aim to get is 2 strings i.e. string1 = Address and string2 = 0000:ae:05.2 but I also need the 1st line to be treated similarly so basically it all should start from string1 = header and string2 = 0000:ae:05.2

My code looks like that at the moment:

int main(int argc, char* argv[])
{
std::string nStr = 
R"(
"0000:ae:05.2:
Address: 0000:ae:05.2
Segment: 0x0000
")";
std::string tLine1="", tLine2="";

//nStr = nStr.erase(nStr.find_last_not_of("\n\r\t"));   

const std::string delimiter = ": ", delim2=":";

std::string::size_type pos = nStr.find(delimiter);
std::string::size_type pos2 = nStr.find(delim2);

if(nStr.npos != pos){
    tLine2 = nStr.substr(pos + 1);
    tLine1 = nStr.substr(0, pos);
}
else if(nStr.npos != pos2){
    tLine1 = nStr.substr(0, pos2);
    tLine2 = "blank";
}
else
    std::cout << "Delimiter not specified!\n";

What does it works for the "main" delimiter, the ": " and not for the ":". Also it does not read all the ": " delimiters.

My output would be: tLine1= "0000:ae:05.2: Address tLine2= 0000:ae:05.2 Segment: 0x0000

Any thoughts on how this can be done correctly? Or how to approach this in a better way? Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire