c++ - 删除一行中一个字符前的所有空格

标签 c++

我有一个特殊的要求,我需要删除管道“|”这一特定字符之前的所有空格字符。 我已经为它编写了一个测试代码,它实际上打印了正确的输出,但另外还给了我一个核心文件:(

我的代码如下:

int main()
{

    string line="1  2  |3 4| hbvhwf     wjff wenf|hjbcwbfw     ejwef   efwk    dfkwe|jsv                       |";
    cout <<line<<endl;
    string::iterator ite =(line.begin());

    int counter=0;
    int index=0;
    int start=0;
    while(ite != (line.end()))
    {
        if(*ite == '|' && counter > 0)
        {
            line.erase(start,counter);
            counter=0;
            cout<<line<<endl;
        }
        if(ite!=line.end())
        {
            if(isalnum(*ite))
            {
                counter=0;
            }
            if(*ite==' ')
            {
                if(!counter)
                {
                    start=index;
                }
                counter++;
            }
            ite++;
            index++;        
        }
    }

    cout<<line<<endl;
}

我正疯狂地寻找核心转储的根本原因。 有人可以帮忙吗? 预期输出是:

1  2|3 4| hbvhwf     wjff wenf|hjbcwbfw     ejwef   efwk    dfkwe|jsv|

最佳答案

正如 Krzysztof 的回答所说,核心转储的原因是 erase() 使迭代器无效。要解决此问题,您需要正确重置迭代器,使用 range versionerase() 中,您将获得一个迭代器,该迭代器引用现在占据第一个被删除字符位置的字符,并将其分配给 ite。将第一个 if 语句更改为下面的代码,它应该可以正常工作。

    if(*ite == '|' && counter > 0)
    {
        ite = line.erase(ite - counter, ite);

        counter=0;
        cout<<line<<endl;
    }

关于c++ - 删除一行中一个字符前的所有空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21335617/

相关文章:

c++ - 虚拟 << 运算符

c++ - 如果在 constexpr 上下文中,如何在 assert() 和 static_assert() 之间分派(dispatch),依赖?

c++ - 这个函数调用真的有歧义吗?

c++ - 派生类的 Push_back shared_ptr

c++ - RapidJSON::Value&的GoogleTest/Mock SaveArg

C++:二叉搜索树适用于整数,但在我尝试传递字符串时崩溃

c++ - 链接 DLL 错误 visual studio

c++ - TCP 中的垃圾值和缓冲区差异

c++ - 在遍历 map 和打印内容时获取向后输出

c++ - lambda 函数的 setter ?