473,699 Members | 2,196 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

printing % with printf(), use of \ (escape) character

Hi,

'C' says \ is the escape character to be used when characters are
to be interpreted in an uncommon sense, e.g. \t usage in printf(),
but for printing % through printf(), i have read [pg.154 of 'The C
programming language' -kernighan, Ritchie] that %% should be used.
Wouldn't it have been better (from design perspective) if the same
escape character had been used in this case too.

Forgive me for posting without verfying things with any standard
compiler, i don't have the means for now.

tiro.

Nov 14 '05 #1
7 96307


te*******@yahoo .com wrote:
Hi,

'C' says \ is the escape character to be used when characters are
to be interpreted in an uncommon sense, e.g. \t usage in printf(),
but for printing % through printf(), i have read [pg.154 of 'The C
programming language' -kernighan, Ritchie] that %% should be used.
Wouldn't it have been better (from design perspective) if the same
escape character had been used in this case too.

Forgive me for posting without verfying things with any standard
compiler, i don't have the means for now.


The two conventions "escape" from two different
processing mechanisms operating at two different levels.

The \ escape tells the C compiler to do something
unusual, like generating a single tab character when it
sees a \ followed by a t. The compiler does what it does,
and when all's done your program has a string containing
a tab character; both the \ and the t are gone. They have
gone, in a sense, to the same place the " quotes went: they
were source-code constructs that produced some effect in
the finished program and then vanished, leaving only the
program itself behind.

So now you've got a program with some strings in it,
and the strings don't contain any backslash characters
(unless you created them with the source sequence \\, of
course). Now you hand one of these strings to printf() as
a format, and printf() starts copying the format string's
characters to the output. (Note that there's nothing special
about the tab character; printf() just copies it the same
way it copies H e l l o.) However, you need a way to tell
printf() to stop copying and do something else, like output
the characters that represent an integer value. So printf()
is sensitive to the % character, which means "stop copying
and do something different, as specified by the next few
characters (which also aren't copied)."

Of course, this means you can't output a % character by
just copying it from the format; as soon as printf() sees %
it switches into "do something special" mode. So to make it
possible to output a percent sign, printf() recognizes the
sequence %% as "do something special, to wit, output a %
character."

printf() could have been designed to use something other
than the % character as its "special stuff" marker; in fact,
it could perfectly well have used the backslash character.
But remember that it takes extra effort to get the compiler
to generate a backslash character in a string: backslash means
"special stuff" to the compiler, so you need to write two of
them to generate one as "payload." Your printf() formats
would wind up looking like

printf ("Answer = \\d\n", 42);

That might not look too awful, but consider: this different
printf() would also need a way to output an actual backslash
character, just as the real printf() needs a special mechanism
to output a percent sign. Well, how about doubling them up?

printf ("Answer between backslashes = \\\\\\d\\\\\n", 42);

Ugh, and double ugh. (Sadly, many "regular expression" packages
run into exactly this problem: they use \ as their own "special"
indicator, and they double it to mean "just an ordinary backslash
after all," and then it gets doubled again to push it through the
C compiler ... Trying to read regular expression strings embedded
in C source code can make your eyes go twisty.)

Summary: Different escape mechanisms to talk to different
entities that operate at different times.

--
Er*********@sun .com

Nov 14 '05 #2
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

te*******@yahoo .com wrote:
Hi,

'C' says \ is the escape character to be used when characters are
to be interpreted in an uncommon sense, e.g. \t usage in printf(),
but for printing % through printf(), i have read [pg.154 of 'The C
programming language' -kernighan, Ritchie] that %% should be used.
Wouldn't it have been better (from design perspective) if the same
escape character had been used in this case too.


That's both correct, and wrong. You've confused two different things, C
character "escape sequences" and printf() format sequences.

C recognizes that certain characters cannot be easily entered into a program as
data (like the "backspace" character, the "newline" character, or even the "tab"
character). For those characters, C recognizes a simple two-character escape
sequence consisting of a '\' followed by a second character from a limited set.
Since the '\' character is part of this escape sequence, there is a special
escape sequence jut to reproduce the '\' character.

So, you get '\t' for a tab character, '\n' for a newline character, '\\' for the
backslash character, and so on, for about 10 or so characters. These values can
be used whereever a character data item is entered; for instance
char TabChar = '\t'; /* for a single tab character */
char MSDOS_Path[] = "C:\\MSDOS\ \"; /* for the backslash character */

You can even printf() with these characters...
printf("\n\n\tT his line is two down, and one tabstop in \n");

Now, printf() is a function that, as it's first argument, takes a string that
tells it what format the rest of the arguments are. This string also provides
some constants that seperate the values represented by the other arguments when
printf() reproduces it's data to stdout.

The printf() function uses the '%' character in the format string to delimit
where it is to insert the next argument, and to provide a format and data type
for that argument. Of course, this means that, _in the format string_, if you
want a percent character to be reproduced verbatum, you'll have to escape it
according to the rules that printf() uses; "%%" _as a format string_ causes
printf() to reproduce a single percent sign instead of looking for the next
argument.

But, this isn't the only way to get printf() to reproduce the percent sign. You
can give printf() a character or string argument consisting of an _unescaped_
percent sign as any of the arguments _other than the format string.

So, here's an example...

printf("Three percents:\n1 %%\n2 %c\n3 %s\n",'%',"%");

- --
Lew Pitcher
IT Specialist, Enterprise Data Systems,
Enterprise Technology Solutions, TD Bank Financial Group

(Opinions expressed are my own, not my employers')
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.4 (MingW32)

iD8DBQFCAo9NagV FX4UWr64RAlCIAJ 9tsBzq4mkLaw/6DnbBcVm3YlcuoA CfcckA
xJYRuCoA5dPmRe1 rzJ2k02k=
=yXLB
-----END PGP SIGNATURE-----
Nov 14 '05 #3
Hi Eric,
Thanks for the response,
i am sorry for a late reply,
i am a newbie in the C world.
--------------------------------
Note that there's nothing special
about the tab character; printf() just copies it the same
way it copies H e l l o.) However, you need a way to tell
printf() to stop copying and do something else, like output
the characters that represent an integer value. So printf()
is sensitive to the % character, which means "stop copying
and do something different, as specified by the next few
characters (which also aren't copied)." -----------------------------------------------
can't that be implemented by using a different character with \, for
e.g., they could have said to printf to consider \ as a special
character and said, take \d as a sign of representing corresponding
variale as a decimal
i.e. instead of saying \\d for the purpose, we could use \d or some \k
(if d is alreay in use)
the fact that printf() and c compiler work at different levels should
make it more feasible
tiro.
Eric Sosman wrote: te*******@yahoo .com wrote:
Hi,

'C' says \ is the escape character to be used when characters are to be interpreted in an uncommon sense, e.g. \t usage in printf(),
but for printing % through printf(), i have read [pg.154 of 'The C
programming language' -kernighan, Ritchie] that %% should be used.
Wouldn't it have been better (from design perspective) if the same
escape character had been used in this case too.

Forgive me for posting without verfying things with any standard
compiler, i don't have the means for now.


The two conventions "escape" from two different
processing mechanisms operating at two different levels.

The \ escape tells the C compiler to do something
unusual, like generating a single tab character when it
sees a \ followed by a t. The compiler does what it does,
and when all's done your program has a string containing
a tab character; both the \ and the t are gone. They have
gone, in a sense, to the same place the " quotes went: they
were source-code constructs that produced some effect in
the finished program and then vanished, leaving only the
program itself behind.

So now you've got a program with some strings in it,
and the strings don't contain any backslash characters
(unless you created them with the source sequence \\, of
course). Now you hand one of these strings to printf() as
a format, and printf() starts copying the format string's
characters to the output. (Note that there's nothing special
about the tab character; printf() just copies it the same
way it copies H e l l o.) However, you need a way to tell
printf() to stop copying and do something else, like output
the characters that represent an integer value. So printf()
is sensitive to the % character, which means "stop copying
and do something different, as specified by the next few
characters (which also aren't copied)."

Of course, this means you can't output a % character by
just copying it from the format; as soon as printf() sees %
it switches into "do something special" mode. So to make it
possible to output a percent sign, printf() recognizes the
sequence %% as "do something special, to wit, output a %
character."

printf() could have been designed to use something other
than the % character as its "special stuff" marker; in fact,
it could perfectly well have used the backslash character.
But remember that it takes extra effort to get the compiler
to generate a backslash character in a string: backslash means
"special stuff" to the compiler, so you need to write two of
them to generate one as "payload." Your printf() formats
would wind up looking like

printf ("Answer = \\d\n", 42);

That might not look too awful, but consider: this different
printf() would also need a way to output an actual backslash
character, just as the real printf() needs a special mechanism
to output a percent sign. Well, how about doubling them up?

printf ("Answer between backslashes = \\\\\\d\\\\\n", 42);

Ugh, and double ugh. (Sadly, many "regular expression" packages
run into exactly this problem: they use \ as their own "special"
indicator, and they double it to mean "just an ordinary backslash
after all," and then it gets doubled again to push it through the
C compiler ... Trying to read regular expression strings embedded
in C source code can make your eyes go twisty.)

Summary: Different escape mechanisms to talk to different
entities that operate at different times.

--
Er*********@sun .com


Nov 14 '05 #4


te*******@yahoo .com wrote:
Hi Eric,
Thanks for the response,
i am sorry for a late reply,
i am a newbie in the C world.
--------------------------------
Note that there's nothing special
about the tab character; printf() just copies it the same
way it copies H e l l o.) However, you need a way to tell
printf() to stop copying and do something else, like output
the characters that represent an integer value. So printf()
is sensitive to the % character, which means "stop copying
and do something different, as specified by the next few
characters (which also aren't copied)."


-----------------------------------------------
can't that be implemented by using a different character with \, for
e.g., they could have said to printf to consider \ as a special
character and said, take \d as a sign of representing corresponding
variale as a decimal
i.e. instead of saying \\d for the purpose, we could use \d or some \k
(if d is alreay in use)
the fact that printf() and c compiler work at different levels should
make it more feasible


printf() could have been defined to use \ instead of %.
Any character other than '\0' could have been used: & or #
or Q or ' ' or : or anything you can imagine.

However, if \ had been chosen there would have been a
problem. Let's suppose \ were the chosen character; here
are some output formats you might try to use:

printf ("\d\n", 1);
printf ("\x\n", 2u);
printf ("\07d\n", 3);
printf ("\f\n", 4.0);

None of these would work as you want them to. The first
would cause the compiler to complain about an unknown escape
sequence; '\d' is not a defined character escape. The second
would also provoke a complaint, because when the compiler sees
\x it expects to find some hexadecimal digits next, as in
"\x1b" -- the \x without its hex digits is an undefined escape
sequence.

The final two would compile, but the results would disappoint
you. The third attempts to print a decimal number in a seven-
digit field with leading zeroes, but what it actually does is
print the two characters '\07' and '\n' without converting any
numbers at all -- on an ASCII system, this rings the bell and
starts a new line. The fourth is trying to convert a floating-
point number, but what it actually prints is a form feed followed
by a new line; nothing gets converted.

All these problems are because \ in a string literal changes
the meaning of the next few characters. To prevent that from
happening and to get an actual \ into the string so printf()
could find it, you would need to write

printf ("\\d\n", 1);
printf ("\\x\n", 2u);
printf ("\\07d\n", 3);
printf ("\\f\n", 4.0);

Here's the fact you seem to be overlooking: printf() doesn't
see the format string until after the compiler has processed it.
The compiler applies the same rules to the printf() format string
as it does to any other string literal: it processes \ escapes,
it splices adjacent literals together, and so on, doing exactly
the same thing for printf()'s format as for every other string
literal in the source code. printf() is not a special case.

--
Er*********@sun .com

Nov 14 '05 #5

On Thu, 10 Feb 2005 te*******@yahoo .com wrote:

Hi Eric,
Thanks for the response,
i am sorry for a late reply,
i am a newbie in the C world.


You're also a newbie in the Usenet world. For future reference:
(1) Trim away any part of the last message that you're not responding
to. (2) You should attribute quotes properly, like this:

Eric Sosman wrote:
Note that there's nothing special
about the tab character; printf() just copies it the same
way it copies H e l l o.) However, you need a way to tell
printf() to stop copying and do something else, like output
the characters that represent an integer value. So printf()
is sensitive to the % character, which means "stop copying
and do something different, as specified by the next few
characters (which also aren't copied)."


[C]an't that be implemented by using a different character with \, for
e.g., they could have said to printf to consider \ as a special
character and said, take \d as a sign of representing corresponding
variale as a decimal


No. What is "\d"? It doesn't exist. There is no escape code \d;
that's just a syntax error. (Try it!) The escape codes in C are
\n, \t, \a, \b, \v, \\, \", \', and probably a few more I didn't mention.
So the C code

char *a = "\d";

contains a syntax error. For the same reason, the C code

printf("\d");

contains the same syntax error. Now, we could write

printf("\\d");

That would print a backslash (keyed by the escape code \\) followed
by the letter d.

The printf function happens to associate special actions with the
percent sign, %. So for example we can write

char *a = "%s\n"; /* percent sign, s, escape-code-for-newline */
printf(a, a);

That tells the compiler to pass the string 'a' (a string of length 3
containing the characters '%', 's', and '\n', with a null byte at the
end of the string) to 'printf' as both the first and the second argument.
'printf' sees the percent sign followed by an 's', and prints the value
of the second argument:

%s (newline)

Then it sees the newline and echoes it to the screen.

(newline)

So the output is "%s" followed by two newlines.
Read that through slowly and work it out on paper. Does it make
more sense now?

HTH,
-Arthur
Nov 14 '05 #6
Hi,
i got it through the below explanation

Eric Sosman wrote:
"Here's the fact you seem to be overlooking: printf() doesn't
see the format string until after the compiler has processed it.
The compiler applies the same rules to the printf() format string
as it does to any other string literal: it processes \ escapes,
it splices adjacent literals together, and so on, doing exactly
the same thing for printf()'s format as for every other string
literal in the source code. printf() is not a special case."

thank u

Eric Sosman wrote: te*******@yahoo .com wrote:
Hi Eric,
Thanks for the response,
i am sorry for a late reply,
i am a newbie in the C world.
--------------------------------
Note that there's nothing special
about the tab character; printf() just copies it the same
way it copies H e l l o.) However, you need a way to tell
printf() to stop copying and do something else, like output
the characters that represent an integer value. So printf()
is sensitive to the % character, which means "stop copying
and do something different, as specified by the next few
characters (which also aren't copied)."


-----------------------------------------------
can't that be implemented by using a different character with \, for e.g., they could have said to printf to consider \ as a special
character and said, take \d as a sign of representing corresponding
variale as a decimal
i.e. instead of saying \\d for the purpose, we could use \d or some \k (if d is alreay in use)
the fact that printf() and c compiler work at different levels should make it more feasible


printf() could have been defined to use \ instead of %.
Any character other than '\0' could have been used: & or #
or Q or ' ' or : or anything you can imagine.

However, if \ had been chosen there would have been a
problem. Let's suppose \ were the chosen character; here
are some output formats you might try to use:

printf ("\d\n", 1);
printf ("\x\n", 2u);
printf ("\07d\n", 3);
printf ("\f\n", 4.0);

None of these would work as you want them to. The first
would cause the compiler to complain about an unknown escape
sequence; '\d' is not a defined character escape. The second
would also provoke a complaint, because when the compiler sees
\x it expects to find some hexadecimal digits next, as in
"\x1b" -- the \x without its hex digits is an undefined escape
sequence.

The final two would compile, but the results would disappoint
you. The third attempts to print a decimal number in a seven-
digit field with leading zeroes, but what it actually does is
print the two characters '\07' and '\n' without converting any
numbers at all -- on an ASCII system, this rings the bell and
starts a new line. The fourth is trying to convert a floating-
point number, but what it actually prints is a form feed followed
by a new line; nothing gets converted.

All these problems are because \ in a string literal changes
the meaning of the next few characters. To prevent that from
happening and to get an actual \ into the string so printf()
could find it, you would need to write

printf ("\\d\n", 1);
printf ("\\x\n", 2u);
printf ("\\07d\n", 3);
printf ("\\f\n", 4.0);

Here's the fact you seem to be overlooking: printf() doesn't
see the format string until after the compiler has processed it.
The compiler applies the same rules to the printf() format string
as it does to any other string literal: it processes \ escapes,
it splices adjacent literals together, and so on, doing exactly
the same thing for printf()'s format as for every other string
literal in the source code. printf() is not a special case.

--
Er*********@sun .com


Nov 14 '05 #7
i got it through the below explanation

Eric:
"Here's the fact you seem to be overlooking: printf() doesn't
see the format string until after the compiler has processed it. "


thank u

Nov 14 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
21409
by: Alden Streeter | last post by:
Here is the HTML that is being output by my asp page: <a href='Files/category/computers/bigimages/computers-sub-monitors.jpg' target='_blank' onMouseOver="window.status='Click for a larger image of MONITOR, 19\" CODAR EAGLE.';return true;" onMouseOut="window.status='';return true;"> <img width='98' height='96' border='0' src='Files/category/computers/bigimages/computers-sub-monitors.jpg' alt='MONITOR, 19" CODAR EAGLE'></a>
1
6202
by: Grant Allen | last post by:
I know this has been asked before - I've trawled through the mail archives and FAQs looking for any info, and only found "that's the way it works" answers. Basically, I want to turn off backslash ( \ ) as an escape character in string literals. It makes porting apps to PostgreSQL much more difficult, because no major rdbms behaves this way (at least, none of Oracle, SQL Server,DB2, Sybase, Informix, SQL Anywhere or SQL Base ... the one's...
3
41867
by: newsgroupie | last post by:
Hi Newsgroupies, Please could someone tell me the escape character for " (double quote) in a string.Format(...) method as \x22 doesn't work as it comes out as \" in the result. i.e. string.Format("you say \x22goodbye\x22 and I say \x22hello\x22"); ....comes out as...
7
22586
by: Steve | last post by:
string str ="\"C:\Program Files\Internet Explorer\iexplore.exe\" -nohome" How can I remove charcter to string str = ="C:\Program Files\Internet Explorer\iexplore.exe -nohome"
3
2609
by: Steve | last post by:
The string in registry is "rundll32.exe C:\Program Files\INTERN~1\hmmapi.dll,OpenInboxHandler" After opensubkey and getregistry, I got "rundll32.exe \"C:\\Program Files\\INTERN~1\\hmmapi.dll\",OpenInboxHandler" Is there anyway I can get the string exactly in registry without escape character?
12
9634
by: Jeff S | last post by:
In a VB.NET code behind module, I build a string for a link that points to a JavaScript function. The two lines of code below show what is relevant. PopupLink = "javascript:PopUpWindow(" & Chr(34) & PopUpWindowTitle & Chr(34) & ", " & Chr(34) & CurrentEventDetails & ")" strTemp += "<BR><A HREF='#' onClick='" & PopupLink & "'>" & EventName & "</A><BR>" The problem I have is that when the string variables or contain a string with an...
6
27785
by: HK guy | last post by:
In C#, it has a escape chatacter @ then can ingnore all the escape charactrer in string, how about in VB.NET, any escape character like @? Thank you
15
18315
by: pkaeowic | last post by:
I am having a problem with the "escape" character \e. This code is in my Windows form KeyPress event. The compiler gives me "unrecognized escape sequence" even though this is documented in MSDN. Any idea if this is a bug? if (e.KeyChar == '\e') { this.Close(); }
5
7880
by: Jeremy Rohrer | last post by:
What is the python code for printing this sentence? "The \t is the tab escape character."
0
8697
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9184
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9045
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8930
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8892
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7767
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5878
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4382
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
2359
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.