leocod
leocod

Reputation: 173

Printing control characters using escaped notation

I need help understanding what are they really asking here. I have written part of the program already. Do I have to print the decimal value for the newline character and the tab character? Why I can't get 10 pair per line all the time? Sometimes I get 10 pairs and another times not.

The assignment was:

Write a program that reads input as a stream of characters until encountering EOF. Have the program print each input character and its ASCII decimal value.

Note that characters preceding the space character in the ASCII sequence are nonprinting characters. Treat them specially. If the nonprinting character is a newline or tab, print \n or \t, respectively. Otherwise, use control-character notation. For instance, ASCII 1 is Ctrl+A, which can be displayed as ^A. Note that the ASCII value for A is the value for Ctrl+A plus 64. A similar relation holds for the other nonprinting characters. Print 10 pairs per line, except start a fresh line each time a newline character is encountered.

This is what I have written:

#include <stdio.h>

    int main(void)
    {
    int ch;
    int i=0;

    printf("Please enter some characters.\n\n");

    while((ch=getchar()) != EOF)
    {
    if((i%10) == 0)
        printf("\n");

    if (ch == '\n')
        printf( "\n\\n ");
    else if (ch == '\t')
        printf("\\t %d ", ch);
    else if (ch < ' ')
        printf("^%c %d  ", ch+64, ch);
    else
        printf("%c %d  ",ch, ch);

    i = i+1;
    }
    return 0;
    }

Upvotes: 1

Views: 3217

Answers (3)

Anthony Bellew
Anthony Bellew

Reputation: 31

ASCII 0-31 are non-printing characters. Their respective control-character notations can be found at the ASCII Wikipedia page in the [b] column.

You will want to print the control-character notation for these characters, with the exception of 9 and 10, for which you will print \t and \n (backslash-t and backslash-n), respectively.

Another thing about your loop

if((i%10==0) || (ch == '\n'))
printf("\n");

These should be two separate statements. Make sure to escape your backslashes with an extra backslash beforehand as printf("\\n"); will actually print "\n" (backslash-n) whereas printf("\n") will just print an actual line feed, which I'm almost certain is not what your instructor is asking for here, except after each ten entries.

Upvotes: 2

alfa
alfa

Reputation: 3088

Have a look at the Wikipedia pages about ASCII, the caret notation (which is similar to control notation). I don't want to post the solution here. :D

Upvotes: 0

mah
mah

Reputation: 39807

What they're asking for sounds very clear; here is some pseudo-code:

if (ch == '\n') print "\n %d", ch;
else if (ch == '\t') print "\t %d", ch;
else if (ch < ' ') { print "^"; print "%c %d", ch+'A', ch; }
else print "%c %d",ch, ch;

This is exclusive of formatting needed to make it look right; your code already has some formatting.

Upvotes: 3

Related Questions