-2

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?

Himanshu Verma
  • 131
  • 1
  • 10
  • Please don't spam with tags, especially with tags of unrelated languages. – Some programmer dude Dec 20 '19 at 08:57
  • 3
    Strings do not magically expand when you assign to non-existent elements. Instead, the behaviour is undefined and anything can happen. – molbdnilo Dec 20 '19 at 08:58
  • 2
    As for your problem, think about the size of `rMessage`... You never set its size anywhere, so any indexing of it will be *out of bounds* and lead to *undefined behavior*. – Some programmer dude Dec 20 '19 at 08:58
  • 3
    Lastly, Please read about the [`std::isalnum`](https://en.cppreference.com/w/cpp/string/byte/isalnum) function. And C++ have many nice [algorithm](https://en.cppreference.com/w/cpp/algorithm) functions, for example to conditionally copy elements of a container to another container (with [`std::copy_if`](https://en.cppreference.com/w/cpp/algorithm/copy), which could be used instead of your current loop). – Some programmer dude Dec 20 '19 at 08:58
  • 1
    Don't `operator[]` assign to `rmessage` because it doesn't yet have reserved capacity. Rather use [`operator+=`](https://en.cppreference.com/w/cpp/string/basic_string/operator%2B%3D) or [`append`](https://en.cppreference.com/w/cpp/string/basic_string/append) – acraig5075 Dec 20 '19 at 08:58
  • Does this answer your question? [Function to trim non, alphabetic, numeric characters from character array](https://stackoverflow.com/questions/13412667/function-to-trim-non-alphabetic-numeric-characters-from-character-array) – arsdever Dec 20 '19 at 10:30
  • Please try to make your question title more informative and legible. Also a tip: try to avoid `using namespace std;`. Just use `std::cout` et cetera. – mand Dec 20 '19 at 10:53

1 Answers1

3

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.

acraig5075
  • 10,588
  • 3
  • 31
  • 50