printf characters as hex in C

I want to count the character frequency in a string and print them as hexadecimal.How can this be done with following code?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <stdio.h>
#include <conio.h> 
#define NCHAR 256

main()
{    
  char inputString[100];    
  int index, frequency[NCHAR];    
  printf("Enter a String\n");    
  gets(inputString);    

  for(index=0; inputString[index] != '\0'; index++)
  {                
    frequency[inputString[index]]++;   
  }       
  printf("\nCharacter   Frequency\n");    

  for(index=0; index < NCHAR; index++)
  {        
    if(frequency[index] != 0)
    {            
      printf("%5c%10d\n", index, frequency[index]);                            
    }   
  }   
  getch();   
 
  return 0;
}
Last edited on
closed account (E0p9LyTq)
http://www.cplusplus.com/reference/cstdio/printf/

Look at the format specifiers.
What I want to do is following: Charatcters like alphabet,numbers etc. with printf above and just the escape sequences (\t , \n etc) as hex.I want to create a char with all escape characters and check it with frequency[index].If escape sequence printf hex,if not "normal" printf like above.But it doesn't work.Could someone help me out?
Has someone an idea please?
Please...Anyone...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <stdio.h>
#include <ctype.h> // isprint

int main()
{
    const char cstr[] = "ab\tcd\ne\tf\n" ;

    // print one character per line, with \t \n etc. as hex
    for( int i = 0 ; cstr[i] != 0 ; ++i )
    {
        // http://www.cplusplus.com/reference/cctype/isprint/
        if( isprint( cstr[i] ) ) printf( "%c\n", cstr[i] ) ; // print normal characters as they are
        else printf( "%#x\n", cstr[i] ) ; // not a printable character, print its value in hexadecimal
    }
}

http://coliru.stacked-crooked.com/a/3a7a9d360a482a34
Thank you very much.But I didn't understand cstr.Why does "ab\tcd\ne\tf\n"; mean?
\t and \n is clear but why ab\tcd..
Last edited on
closed account (E0p9LyTq)
I didn't understand cstr.Why does "ab\tcd\ne\tf\n"; mean?


1
2
3
4
5
6
7
8
#include <stdio.h>

int main ()
{
   const char cstr[] = "ab\tcd\ne\tf\n" ;

   printf("%s", cstr);
}


ab      cd
e       f
"ab\tcd\ne\tf\n"; doesn't mean anything. It's (just) test data, which includes printable (abcdef) and non-printable (control) chars ('\t' and '\n') to show that the output logic works ok (as explained by JLBorges's comments!)

Andy
Last edited on
Topic archived. No new replies allowed.