Search code examples
c++xcodenew-operator

A quick question from a newbie about deleting non-Upper-alpha: why isn't my code working?


Hi I am trying to delete all the non-capitalized alphabet from a string input, but I am not quite sure where the error is in my coding. Please comment if you know why!

#include <iostream>
#include <string>
#include <cctype>
using namespace std;

string CreateAcronym(string userPhrase) {
int i;
int stringSize;
char charAti;

stringSize = userPhrase.size();

for (i=0 ; i < stringSize ; i++ ) {
   charAti = userPhrase.at(i);
   if ( !isupper(charAti)) {
      userPhrase.erase(i,1);
   }
}
return userPhrase;
}

int main() {
string userSentence;

getline(cin , userSentence);

cout << CreateAcronym(userSentence) << endl;

return 0;
}

Solution

    • You cached old string length and continued to use while the string will become shorter by erasing characters.
    • You skip characters after characters to erase because i++ isn't canceled after erasure.
    stringSize = userPhrase.size();
    
    for (i=0 ; i < stringSize ; i++ ) {
       charAti = userPhrase.at(i);
       if ( !isupper(charAti)) {
          userPhrase.erase(i,1);
       }
    }
    

    should be

    for (i=0 ; i < static_cast<int>(userPhrase.size()) ; ) {
       charAti = userPhrase.at(i);
       if ( isupper(charAti)) {
          i++;
       } else {
          userPhrase.erase(i,1);
       }
    }