std::string::find always returns string::npos even

雨燕双飞 提交于 2019-12-12 04:13:28

问题


std::string::find is always returning string::npos even if it's supposed to find something. In this case I'm trying to find a { followed by a new line. But no matter what string I put there, it won't find it.

pos=0;
while(pos!=string::npos)
{
    ko=input.find("{\n"); //here is the problem!!!
    if(ko!=string::npos && input[ko]=='\n')
    {
        input.erase(ko, 3);
        kc=input.find("}", ko);
        for(pos=input.find("\",", ko); pos<kc; pos=input.find("\",\n", pos))
        {
            input.erase(pos, 4);
            input.insert(pos, " | ");
        }
        pos=input.find("\"\n", ko);
        input.erase(pos, 3);
    }
    else
    {
        break;
    }
}
pos=0;
cn=1;
for(pos=input.find("\"", pos); pos!=string::npos; pos=input.find("\"", pos))
{
    input.erase(pos,1);
    if(cn)
    {
        input.insert(pos,"R");
    }
    cn=1-cn;
}

Here a piece of what input has:

-- declaring identifiers of state and final states
Detecting_SIDS = {
    "Detecting",
    "Detecting_CleanAir",
    "Detecting_GasPresent"
}

-- declaring identifiers of transitions
Detecting_TIDS = {
    "__NULLTRANSITION__",
    "Detecting_t2",
    "Detecting_t3",
    "Detecting_t4",
    "Detecting_t5"
}

This code is supposed to turn this input above to the following:

-- declaring identifiers of state and final states
datatype Detecting_SIDS = RDetecting | RDetecting_CleanAir | RDetecting_GasPresent

-- declaring identifiers of transitions
datatype Detecting_TIDS = RNT | RDetecting_t2 | RDetecting_t3 | RDetecting_t4 | RDetecting_t5

回答1:


I think you should traverse the input with the std::find_first_of algorithm. The return from this is an integrator so your loop should exit on this being equal to std::end(input). Using this iterator you can look ahead to see if the following character is your '\n'.

This is uncompiled code for indication only:

auto ptr = std::begin(input);
auto end = std::end(input);

while(ptr != end) 
{
    ptr = std::find_first_of(ptr, end, '{' );

    if (ptr == end)
        break;

    else if (++ptr == end)
        break;

    else if (*ptr == '\n)
    {
        //Do Processing//
    }
}


来源:https://stackoverflow.com/questions/44488093/stdstringfind-always-returns-stringnpos-even

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!