-1

the input provided through temp is a sentence, and I need to remove spaces and special characters but 'mes' stores only the first word

#include <iostream>
#include <cmath>
using namespace std;
int main(){
char mes[51];
char pas[11];
char tem[51];
cin.getline(tem,51);
cin.getline(pas,11);
for(int i=0;i<51;i++){
    mes[i]='\0';
}
for(int t=0;t<sizeof(pas);t++){
    pas[t]=tolower(pas[t]);
}
for (int i=0;i<50;i++){
    char c=tem[i];
    int ch=(int)c;
    if(( ch >= 65 && ch <= 90) || ( ch >= 97 && ch <= 122)){
        if( ch >= 65 && ch <= 90)
            ch+=32;
        mes[i]=(char)ch;
    }
    else
        continue;
}
cout<<mes<<endl;
  • Should be useful: https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems – Steve May 05 '18 at 01:23
  • Unrelated: `ch >= 65` contains minimal information to the reader. It is also utterly reliant on ASCII encoding being used, usually a safe bet, but why gamble at all? Prefer `ch >= 'A'`. – user4581301 May 05 '18 at 01:26

1 Answers1

0

Notice that you are setting each index in mes to '\0', aka NUL. When you are iterating through tem checking if each character is a letter, you are inadvertently separating the words by \0 inside mes. You need to have a separate index that allows you to add the letters when you find them.

Your for loop could look like this.

int currentIndex = 0;
for (int i = 0; i < 50; i++){
    char c = tem[i];
    int ch = (int)c;
    if(( ch >= 65 && ch <= 90) || ( ch >= 97 && ch <= 122)){
        if( ch >= 65 && ch <= 90)
            ch+=32;
        mes[currentIndex++]=(char)ch;
    }
    else
        continue;
}

This way, you will be adding the letter directly after the next, rather than something like Hello\0World.

Also, remember that cout will only print strings up until it finds a \0 character. Technically you are storing all letters you find in a sentence, but they are separated by \0 and therefore, cout only prints the first word.