hello, I want to create app that will eliminate some letter if condition is met. And I have this code which eliminates 'D' or 'd' characters, but at output i just get the same word. (i.e. if I enter word "dream", at output I get the same, and I expect to get "ream")
here is code:
#include <iostream>
#define LENGTH 12
usingnamespace std;
int main() {
char _word[LENGTH];
cout<<"enter word: ";
cin>>_word;
cout<<"\n"<<_word; //displays how the entered word looks
//before elimination
for(int n=0;n<LENGTH;n++) //repeat down actions until the end of word
{ // is met
if(_word[n]=='d' || _word[n]=='d') { //elimination
_word[n]='\0'; //substitute D or d with \0
}
}
cout<<"\n"<<_word; //print modified word
return 0;
}
This way won't work. When you put a '\0' character in a c-string, this automatically indicates that your string ends there. Nothing after that point will be printed. I'd suggest creating another char array and copying the initial array to the new one, omitting the characters you don't want.
@systempause: i still dont get it, can you pls explain deeper?
@moorecm: remove_if algorith, how could I use it on my example? I found template and example on this site but its still complicated for me. I learn C++ for 4 days
If this is a college assignment then they probably want to see you iterate through the loop yourself. Otherwise moorecm is right and using the STL algorithms is a great solution.
You might also want to consider using std::string rather than a character buffer:
excellent solution too.
btw this wasnt college assignment. I was going through arrays in tutorial on this site, and while reading i got idea to do this task ^^