2017-12-08 7 views
0

2つの文字列でアナグラムをチェックすると、ダブルフリーまたは破損が発生します。アナグラムをチェックするためのアナグラムの2つの文字列をチェックする際に、文字列の空白を削除します。

私のアプローチは、次のとおりです。

ステップ1:両方の入力文字列からすべてのスペースを削除します。

手順2:両方の文字列を並べ替えます。

手順3:長さが異なる場合はfalseを返します。

手順4:すべての文字が一致する場合はtrueを返します。

ときスペースそれがクラッシュして、ユーザー入力。

EX 入力1:Hello Worldの

入力2:sinlge単語のhello世界

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

その作業罰金

#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; 
} 
+0

'userInput2.erase(end_pos1、userInput1.end());'あなたは 'userInput2'から2回消去します。 –

+0

はい:-(私は本当に悪い質問のために申し訳ありませんあなたは答えとしてそれを入れてくださいできますか? – Ysurf

答えて

0

あなたは二回userInput2を消去しています。削除の最初の呼び出しの後に行を変更して、代わりにuserInput1を消去します。

関連する問題