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
  • 565
  • 6
  • 13
  • 25

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
  • 135,547
  • 38
  • 252
  • 361
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
  • 55,009
  • 24
  • 135
  • 201
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
  • 299,747
  • 42
  • 398
  • 622
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
  • 28,120
  • 21
  • 85
  • 141