std::string::find 总是返回 string::npos 甚至 [英] std::string::find always returns string::npos even

查看:36
本文介绍了std::string::find 总是返回 string::npos 甚至的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

std::string::find 总是返回 string::npos 即使它应该找到一些东西.在这种情况下,我试图找到一个 { 后跟一个新行.但是不管我放什么字符串,它都找不到.

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;
}

这里是输入的一部分:

-- 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

推荐答案

我认为您应该使用 std::find_first_of 算法.从 this 返回的是一个积分器,所以你的循环应该在 this 等于 std::end(input) 时退出.使用此迭代器,您可以提前查看以下字符是否是您的 '\n'.

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//
    }
}

这篇关于std::string::find 总是返回 string::npos 甚至的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆