Reputation: 23
We know some escape sequence '\n' - new line but say we don't know if \a, \b, \c .... \z is an escape sequence. How to write a program that allows us to test every character from a to z and/or A to Z in a printf statement or other way to identify an escape sequence and if it is, then print it's value e.g. ouput may look like this:
'\b' is a special character and value of '\b' = 8
This program may look silly but I am not able to find a solution for it... Thanks in advance.
Upvotes: 2
Views: 3886
Reputation: 93700
As Carl Norum pointed out, these are interpreted by the compiler. You can take an approach similar to autoconf (the program which generates configure
scripts):
#!/bin/bash
for LETTER in {a..z}
do
cat > letter.c <<EOF
#include <stdio.h>
int main() { printf("\\\\$LETTER has ASCII value %u\n", "\\$LETTER"[0]); }
EOF
cc -Werror -o letter letter.c > /dev/null 2>&1 && ./letter
done
Output:
\a has ASCII value 7
\b has ASCII value 8
\e has ASCII value 27
\f has ASCII value 12
\n has ASCII value 10
\r has ASCII value 13
\t has ASCII value 9
\v has ASCII value 11
Notes: The reason for a string constant rather than a character constant is simply shell quoting. This relies on gcc
's -Werror
but you could solve that problem in other ways.
Upvotes: 2
Reputation: 112356
This really does sound like a homework assignment, so I'll give you some strong hints:
look at the isprint() function to tell what's printable
look at any handy character chart to see how the various special characters are represented numerically.
To print the value, you simply need a decimal (d
) format in printf.
Upvotes: 0
Reputation: 224864
I think you may be confused about what's happening. The compiler is interpreting those escape sequences, not any runtime behaviour. Your program can't do what you're asking since the \n
or \b
or whatever you want doesn't exist in that format in your program at runtime. Rather, the string contains the actual ASCII value in place of the escape sequence you had to use in your source code since can't type a literal bell character, for example.
Upvotes: 1
Reputation: 145829
Read 5.2.2p2 in Standard C99 document.
Alphabetic escape sequences are:
\a \b \f \n \r \t \v
Upvotes: 4