Kyle Blue
Kyle Blue

Reputation: 331

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

Upvotes: 0

Views: 3165

Answers (2)

Nicol Bolas
Nicol Bolas

Reputation: 474316

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.

Upvotes: 5

R Sahu
R Sahu

Reputation: 206717

The null character is not a printable character. Hence, you don't see anything in the console for the null characters that are written to cin.

Upvotes: 3

Related Questions