Skip to main content

1-14

Quest: page 24


Write a program to print a histogram of the frequencies of different characters in its input.


note

My assumption is that we are counting ascii characters here and not utf-8 or extended char set.

generate test data

generate test data
#include <stdio.h>
#include <stdlib.h>

int main() {
FILE *f = fopen("txt", "w");
if (f == NULL) {
return EXIT_FAILURE;
}
// print every ascii char 3 times
for (int k = 0; k < 3; k++) {
for (int i = 0; i < 128; i++) {
fprintf(f, "%c", i);
}
}
fclose(f);
return EXIT_SUCCESS;
}
compile and run
gcc gentxt.c -o gentxt.out && ./gentxt.out
tip

use ctype.h to to import isascii => checkif char is ascii.

char histogram

read char historgram
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>

#define MAX 128

int main() {
int c;
int chars[MAX] = {0};
while ((c = getchar()) != EOF) {
if (isascii(c)) {
chars[c]++;
}
}
for (int i = 0; i < MAX; i++) {
if (chars[i] > 0) {
printf("ascii %d: %d times\n", i, chars[i]);
}
}

return EXIT_SUCCESS;
}
note

i am using the '<' operator to pipe the contents of txt to my program. standard streams wiki The output tells us which char on the ascii table and how many times.

compile and run
gcc main.c && ./a.out < txt
ascii 0: 3 times
...
ascii 126: 3 times
ascii 127: 3 times