Painguy
Painguy

Reputation: 567

Print pointer character as hexadecimal

#include <stdio.h>

int main(){
    char *c="";
    printf("Input: ");
    scanf_s("%c", c);
    printf("%x", *c);
}

I want to input a few characters, and then output the entire string as a hexadecimal value. How do I do this?

Upvotes: 0

Views: 727

Answers (4)

EvilTeach
EvilTeach

Reputation: 28837

#include <stdio.h>

int main(void)
{
    unsigned int i = 0;              /* Use unsigned to avoid sign extension */
    while ((i = getchar()) != EOF)   /* Process everything until EOF         */
    {
        printf("%02X ", i);
    }

    printf("\n");

    return 0;
}

Upvotes: 0

zwol
zwol

Reputation: 140669

You need a buffer, not a string constant, to read into. Also, never use any of the *scanf functions, and never use any of the *_s functions either.

The correct way to write your program is something like this:

int
main(void)
{
  char line[80];
  char *p;

  fputs("Input: ", stdout);
  fgets(line, sizeof line, stdin);

  for (p = line; *p; p++)
    printf("%02x", *p);

  putchar('\n');
  return 0;
}

... but I'm not sure exactly what you mean by "output the entire string as a hexadecimal value" so this may not be quite what you want.

Upvotes: 2

Richard J. Ross III
Richard J. Ross III

Reputation: 55573

Your entire code is wrong. It should look something like this:

printf("Input: ");

char c = fgetc(stdin);
printf("%X", c);

Upvotes: 1

Mark Ransom
Mark Ransom

Reputation: 308216

You need a loop to read multiple characters and output each of them. You probably want to change the format to %02x to make sure each character outputs 2 digits.

Upvotes: 0

Related Questions