Simple question (I Hope...) C++, programming

Started by
4 comments, last by Zahlman 17 years, 12 months ago
I am trying to eliminate/remove spaces from a chacter array (and later will be trying to eliminate similar characters) but I have been having really bad luck with it. The method I have been trying is simply moving the non-space characters into a new array via this bit of programming: for (k=0; k<length; k++) { if (encrypter[k]!=' ') { holder=encrypter[k]; i++; } } length=strlen(holder); cout<<"length:"<<length; k=0; cout<<"\n"; for (k=0; k<length; k++) cout<< holder[k]; Problem is the length of the line doesn't seem to be consistent and my out put can be perfect of amazingly flawed from use to use (with the first use usually being the perfect one). I tried googling it but I couldn't find much sort of some weird memory stuff involved in character arrays which I don't fully understand. Oh and just in case its important my delaractions and inputs are as follows: char encrypter[128], holder[128]; int i(0), k(0), length; cin.getline(encrypter,128); length=strlen(encrypter); for (k=0; k<length; k++) encrypter[k]=toupper(encrypter[k]); And that should be all I have that pertains to the program in question. I have tried a few other methods as well, but unless their is a glaring and consistent flaw in my logic I am going to have to guess I missed out one something about arrays...
Advertisement
The thing is that C++ native strings must end with a character '\0'. When you call "length=strlen(holder);", what strlen does is try to find this '\0' character. Because your loop does not write it to the end of the holder-string, the '\0' character may be somewhere far away in memory and thus strlen returns something crazy.

Before the line "length=strlen(holder);" add this: "holder = '\0';". You can also just write "holder = 0;".

Another alternative is that the first for loop "for (k=0; k<
What I was supposed to say, but incredibly bad forum software prevented, was:

Another alternative is that the first for loop "for (k=0; k < length; k++)" could run one step further "for (k=0; k < length+1; k++)". This way it copies the '\0'-character from the encrypter-string.
Well thanks very much for that, I think that is the first time I have actually understood the use of the /0 thing.
That's C. C++:
std::string my_string("this is a string with spaces");my_string.erase(std::remove_if(my_string.begin(), my_string.end(), std::isspace), my_string.end());
(You may need to wrap isspace in a separate function under some compilers).

Σnigma
Quote:Original post by Enigma
That's C. C++:
std::string my_string("this is a string with spaces");my_string.erase(std::remove_if(my_string.begin(), my_string.end(), std::isspace), my_string.end());
(You may need to wrap isspace in a separate function under some compilers).

Σnigma


Quoted for emphasis.

This topic is closed to new replies.

Advertisement