-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

2
  • Null character not showing up in cout Commented Mar 19, 2023 at 6:29
  • @Jason the null isn't printed even if it made it into the string in the first place, it's replaced with \\0 Commented Mar 19, 2023 at 6:39

1 Answer 1

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 
Sign up to request clarification or add additional context in comments.

2 Comments

Alternatively, you could just tell the string constructor what the full length is: string s("Hello\t\0world", 12);
"You need to do the initialization in three steps:..." Technically the last 2 steps that uses += are not initialization.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.