c++ - Why does assertion failed if both values are the same? -


string removenonalphas(string original) {     for(int = 0; < original.size(); ++i){         if(!(original[i] > 64 && original[i] < 91) &&            !(original[i] > 96 && original[i] < 124)){             original[i] = original[i] - original[i];         }     }     return original; } 

//test1.cpp

string test = "abc abc"; cout << removenonalphas(test) << endl; // output = "abcabc" assert(removenonalphas(test) == "abcabc"); // assertion failed 

//why assertion fail above? removenonalphas result("abcabc") same //rhs "abcabc"

original[i] = original[i] - original[i]; 

what makes repaces character '\0' not remove it. because of output not "abcabc" "abc\0abc". '\0' non-printable won't see in output present when compare ==.

instead of replacing charactes in string, create new string while iterating old one:

string removenonalphas(string const& original) {     std::string result;     for(char c : original)        if((c > 64 && c < 91) ||           (c > 96 && c < 124))            result.push_back(c);     return result; } 

note: prefer using std::isalpha instead of hard-coded values.


Comments

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -