0
#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?

Painguy
  • 535
  • 6
  • 13
  • 24

4 Answers4

2

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.

zwol
  • 129,170
  • 35
  • 235
  • 347
1

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

printf("Input: ");

char c = fgetc(stdin);
printf("%X", c);
Richard J. Ross III
  • 54,187
  • 24
  • 128
  • 194
0

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.

Mark Ransom
  • 286,393
  • 40
  • 379
  • 604
0
#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;
}
EvilTeach
  • 27,432
  • 21
  • 83
  • 138