ubisum
ubisum

Reputation: 179

How do I print a string containing a 0 character in the middle?

I need to define an array of chars. One of the chars in the array must be 0.

I tried something like this:

array[i] = '0';

but when I send array to the output with:

cout << array << endl;

the 0 char is interpreted as a string separator, so only the part of array comprised between indices 0 and i-1 is printed.

How should I define the 0 character in such a way that array is printed as a whole sequence of chars, without interruptions? Could the problem depend on the nature of cout (I mean, maybe my assignment of 0 char is correct, but the printing function has some weird behavior I have ignored)?

Thanks for the help.

Upvotes: 3

Views: 2341

Answers (3)

Roberto
Roberto

Reputation: 1

If you just want to send the ASCII character 0, you can write:

char a='0'

or

char a=48

The problem I still don't know how to solve is how to send the null byte to a serial port, because 0 or \0 are the same and always interrupt the string!

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 311048

Character literal (or named as character constant in C) '0' is not the terminating zero of strings. It seems you used either '\0' or integer literal 0 instead of '0'. '\0' or 0 are indeed the terminating zero and has value 0 while '0' for example in ASCII has value 48.

Take into account that you wrote that you are programming in C but showed a C++ code snippet.:)

Upvotes: 1

Dr. Debasish Jana
Dr. Debasish Jana

Reputation: 7118

array[i] = '0'; // ASCII code of 0 as a character goes in
array[i] = 0; // string terminator character, can also be written as '\0', same thing

Upvotes: 1

Related Questions