-2
int main() {
    
    string s = "Hello\t\0world";
    string k = "";
    
    for(auto i =0; i<s.length();i++){
        switch(s[i]){
            case '\t':
                k = k + "\\t";
                break;
            case '\0':
                k = k + "\\0";
                break;
            default:
                k = k + s[i];
        }
    }
    cout<<k;
    return 0;
}

After null character string is ending and not able to get full solution.

Output should be: Hello\t\0world

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • [Null character not showing up in cout](https://stackoverflow.com/questions/47761686/null-character-not-showing-up-in-cout) – Jason Mar 19 '23 at 06:29
  • @Jason the null isn't printed even if it made it into the string in the first place, it's replaced with `\\0` – Alan Birtles Mar 19 '23 at 06:39

1 Answers1

0

The problem is in the initialization of s. The initialization will stop at the null-character embedded in the string.

You need to do the initialization in three steps:

string s = "Hello\t";  // First part of string
s += '\0';  // Add the terminator character
s += "world";  // Add the second part of the string
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • 1
    Alternatively, you could just tell the `string` constructor what the full length is: `string s("Hello\t\0world", 12);` – Remy Lebeau Mar 19 '23 at 06:33
  • 1
    *"You need to do the initialization in three steps:..."* Technically the last 2 steps that uses `+=` are not initialization. – Jason Mar 19 '23 at 07:03