Steve Obbayi
Steve Obbayi

Reputation: 6085

How can I print a NUL character without a space in C?

I have a situation where I have to print out a NUL character if there is no action in a part of my program. Take for example the code below:

char x = '\0';

...

printf("@%c@\n", x);

I want it to print this:

@@

but it prints out

@ @

Whats the correct way not to have the \0 character printed out a space as above?

Upvotes: 2

Views: 6532

Answers (4)

Michael Burr
Michael Burr

Reputation: 340218

You could use the %s specifier with a precision of 1:

printf( "@%.1s@", &x);

This would treat the data in x as '\0' terminated string, but would only ever print at most a single character, so it doesn't matter that there's no '\0' terminator after the character. If x == 0 then it's an empty string, so nothing is printed between the '@' characters.

Of course if you do this you have to pass a pointer to the character rather than the character itself (hence the &x).

Kind of hacky, but I think still within acceptable bounds for the problem.

Upvotes: 0

Sinan Ünür
Sinan Ünür

Reputation: 118128

Slightly more compact form of @codeka's solution:

#include <stdio.h>

int main(void) {
    char x = '\0';
    printf(x ? "@%c@\n" : "@@\n", x);
    return 0;
}

Upvotes: 0

Carl Norum
Carl Norum

Reputation: 224944

What system are you on? That code prints @@ for me. Here's my sample program:

#include <stdio.h>

int main(int argc, char *argv[])
{
  char x = '\0';
  printf("@%c@\n", x);
  return 0;
}

And my log:

$ make
cc -Wall -o app main.c
$ ./app 
@@

Upvotes: 2

Dean Harding
Dean Harding

Reputation: 72658

if (x == 0)
    printf("@@\n");
else
    printf("@%c@\n", x);

It's not actually printing a space, it actually outputs the \0. It's just that whatever you're viewing the text with is displaying the \0 as a space.

Upvotes: 7

Related Questions