在为两个字符串互相检查字符串时,从字符串崩溃中删除空间

时间:2017-12-08 18:59:24

标签: c++ string

在为两个字符串互相检查两个字符串时抛出双重免费或损坏

我检查字谜的方法是:

步骤1:从两个输入字符串中删除所有空格。

第2步:对字符串进行排序。

步骤3:如果长度不同,则返回false。

步骤4:如果所有字符匹配,则返回true。

注意

当用户输入空格时会崩溃。

ex 输入1:hello world

输入2:你好世界

output : *** Error in `./a.out': double free or corruption (out): 0x00000000023ca0b0 ***
Aborted (core dumped)

对于sinlge来说,它的工作很好

#include<iostream>
#include<set>
#include<string>
#include <algorithm>

bool anagrams(std::string usr1,std::string usr2)
{
        if(usr1.length()==usr2.length())
        {

                for(std::string::size_type pos = 0 ; pos<= usr1.length()-1 ; ++pos)
                {
                        if(pos==usr1.size()-1)
                        {
                                if(usr1[pos]==usr2[pos])
                                return true;
                        }

                        if(usr1[pos]==usr2[pos])
                        {
                                continue ;
                        }
                }

        }
        return false;
}

int main()
{
        std::string userInput1;
        std::string userInput2;


        std::getline(std::cin,userInput1);
        std::getline(std::cin,userInput2);

        std::string::iterator end_pos1 = std::remove(userInput1.begin(),userInput1.end(),' ');
        userInput2.erase(end_pos1,userInput1.end());

        std::string::iterator end_pos2 = std::remove(userInput2.begin(),userInput2.end(),' ');
        userInput2.erase(end_pos2,userInput2.end());

        std::sort(userInput1.begin(),userInput1.end());
        std::sort(userInput2.begin(),userInput2.end());

        if(userInput1.empty() || userInput2.empty())
                return 0;
        if(anagrams(userInput1,userInput2))
                std::cout<<"String is anagrams"<<"\n";
        else
                std::cout<<"String  not  anagrams"<<"\n";

        return 0;
}

1 个答案:

答案 0 :(得分:0)

您正在删除userInput2两次。在第一次调用删除后更改行,以便它删除userInput1