Search code examples
c++cppcheck

Why the string is not getting updated and doesn't print anything in the end


CODE:

#include <iostream>
using namespace std;

int main() {

string message, rMessage;
getline(cin,message);

for(int i=0;i<message.length();i++) {

if( (message[i]>='a' && message[i]<='z') ||
    (message[i]>='A' && message[i]<='Z') ||
    (message[i]>='0' && message[i]<='9') ) {

  rMessage[i] = message[i];
}
else {
    continue;
     }
 }
    cout<<"Removed: "<<rMessage;
} 

Problem:

It is showing a blank string in output and string length as 0. Is this code is correct to remove punctuation? What edit we must do resolve the problem?


Solution

  • What edit we must do resolve the problem?

    Change

    rMessage[i] = message[i];
    

    To

    rMessage += message[i];
    

    The reason is given in the comments section of your question.