Kyle Blue Kyle Blue - 23 days ago 18
C++ Question

How to make a null char?

Just working through c++ primer book. Things are going smoothy, however, when using a range for in order to replace all punctuation with null char's, they are replaced with a space (' ') instead.
I cant understand why :/
How do I change this so that punctuation is replace with no character, rather than a space?

Code:

#include <iostream>
#include <string>
#include <cctype>

using std::cout;
using std::endl;
using std::string;

int main()
{
string s1("Hi I'm Greg.");

cout << s1 << endl;

for(char &c : s1){
if(ispunct(c)){
c = '\0';
}
}

cout << s1 << endl;

return 0;
}


Sorry if its a dumb question...
Cheers!

edit:
Compiled in c++14
Here is my output:


Hi I m Greg

Answer

A NUL character is, first and foremost, a character. It isn't nothing; it's a NUL character. That is, the string "some\0thing" is not the same thing as "something". Your particular console renders the "\0" character as a space, but a different console can render it as nothing. But that doesn't change the fact that a NUL character is not nothing.

If you want to remove a character, then what you have to do is shift all of the following characters down.

Comments