Why does printf("%%") print only one percent (%) symbol? [duplicate] - c

This question already has answers here:
How to escape the % (percent) sign in C's printf
(13 answers)
Closed 8 years ago.
When I run this following code:
#include <stdio.h>
#include <conio.h>
void main(){
clrscr();
printf("%%");
getch();
}
I get % as an output?
What might be the reason behind this logic?

That is what printf does: it is print formatted (f for formatted). It uses % as the formatting character. It is the only reserved character and needs to be escaped to represent it self, i.e. %%. See the manual for more information on formatting: printf.
P.S.: Never use a string that is not a part of the program as the first argument. To print a string message that was input by a user, do printf(%s, message);. Otherwise you will have a security hole in your code.

% comes into format specifiers.
Example
When we write printf("%d", 20);, it will print 20 rather than %d. because the compiler treats % as a format specifier. In the mind of the compiler, the meaning of % is somewhat special.
So if you want that "%" should be the output, then you must write printf("%%"). Here the first % sign will suppress the meaning of the % format specifier and will print % as an output.

From the standard ISO/IEC 9899:1999 (E)
7.19.6.1
Each conversion specification is introduced by the character %.
The conversion specifiers and their meanings are:
% - A % character is written. No argument is converted. The complete
conversion specification shall be %%.

For C printf, % is a special character which typically indicates a parameter to substitute at that position: printf("Hello, %s\n", "World!"); results in "Hello, World!". There are lots of different things you can put after the % depending on the data you want to output. So that leaves the problem of "What if I want to print a percent symbol"?
The solution: Use %%.
The same is true of the special escape character \. "\n" means to print a new line. If you want to actually print the forward slash, you have to put it twice \\
See Printf format string and MSDN.

Related

Why the output of printf("%d" +1) is d but printf("%%%d"+1) is %d?

Why is that the output of
#include<stdio.h>
void main()
{
printf("%d"+1);
}
is d but the output of
#include<stdio.h>
void main()
{
printf("%%%d"+1);
}
is %d and not %%d ??
"%d"+1 by pointer arithmetic takes you to the second char in the char array which is d.
In the string literal "%%%d"+1 leaves you with "%%d" which is interpreted as %d by printf. Since %% is escaped to %.
You are doing pointer arithmetic. "%d"+1 is "d" and "%%%d"+1 is "%%d" (it's like you are skipping the first character of the string).
But, as the documentation of printf() explains, the percent sign (%) is a special character in the string format argument of printf(). It introduces a "conversion specifications".
Because it is a special character it needs a special sequence (a conversion specification, in fact) in order to be able to print a literal %. And the conversion specification designated to print a literal % is exactly %%, as you can see from the first row of the conversion specifications table in the docs.
You are using +1 in printf which will in turn skip the one character i.e. % in your case. after skipping %character you will be left with %%d, since %% is used to print % character. Output will be %d.

Use of % in scanf and printf [duplicate]

This question already has an answer here:
Code for printf function in C [duplicate]
(1 answer)
Closed 8 years ago.
What is the exact use of % in scanf and printf? And would scanf and printf work without the % sign? All I could find is that % is the conversion specifier but I want to know how it works actually?
% is simply the symbol used to identify the beginning of a conversion specifier in the format string; why % as opposed to any other symbol is an open question, and probably doesn't have that interesting an answer. The printf and scanf functions search the format string for conversion specifiers to tell them the number and types of additional arguments to expect, and how to format the output (for printf) or interpret the input (for scanf).
To print a literal %, you need to use %%.
printf can work without using a conversion specifier, but you'll be limited to writing literal strings. scanf is pretty useless without it.
The '%' character is used in the format string of the scanf() and print()-like functions from the standard header <stdio.h>, to indicate place holders for variable data of several kinds. For example, the format specifier "%d" is a place holder for a value having type int.
Thus, the variadic function printf() expects additional parameters passed as arguments to the function, the first of them having type int.
The value of this int argument is converted to string, and it will be replace to the place holder "%d".
In the case of scanf(), the situation is similar, but now scanf() is an input function that expects that the user enters in command-line a value fitting on the type indicated by the format specifier. Thus, a format specifier "%d" will expect that the user enters a value of type int.
Since all the arguments in C are passed by value, the input data requires you use the address of the variable, to mimic a by-reference mode of passing arguments.
There are a lot of options and details related to these format specifiers.
Yo need to take a look at the bibliography.
For example, start in Wikipedia:
printf() format string
scanf() format string
The % in a scanf() or printf() is a keyword whose purpose is identify the type of data that will be stored in the named variable. So, in the following example, the compiler would build instructions to accept input data of type integer and store it in the memory location at the address assigned to num1:
int num1;
scanf("%d",&num1);

Difference between \% and %% [duplicate]

This question already has answers here:
Why is percentage character not escaped with backslash in C?
(4 answers)
How to escape the % (percent) sign in C's printf
(13 answers)
Closed 9 years ago.
After reading over some K&R C I saw that printf can "recognize %% for itself" I tested this and it printed out "%", I then tried "\%" which also printed "%".
So, is there any difference?
Edit for code request:
#include <stdio.h>
int main()
{
printf("%%\n");
printf("\%\n");
return 0;
}
Output:
%
%
Compiled with GCC using -o
GCC version: gcc (SUSE Linux) 4.8.1 20130909 [gcc-4_8-branch revision 202388]
%% is not a C escape sequence, but a printf formatter acting like an escape for its own special character.
\% is illegal because it has the syntax of a C escape sequence, but no defined meaning. Escape sequences besides the few listed as standard are compiler-specific. In all likelihood the compiler ignored the backslash, and printf did not see any backslash at runtime. If it had, it would have printed the backslash in the output, because backslash is not special to printf.
Both are not the same. The second one will print %, but in case of the first one, you will get compiler warning:
[Warning] unknown escape sequence: '%' [enabled by default]
The warning is self explanatory that there is no escape sequence like \% in C.
6.4.4.4 Character constants;
says
The double-quote " and question-mark ? are representable either by themselves or by the escape sequences \" and \?, respectively, but the single-quote ' and the backslash \ shall be represented, respectively, by the escape sequences \' and \\.
It is clear that % can't be represented as \%. There isn't any \% in C.
When "%%" is passed to printf it will print % to standard output, but "\%" in not an valid escape sequence in C. Hence the program will compile, but it will not print anything and will generate a warning:
warning: spurious trailing ‘%’ in format [-Wformat=] printf("%");
The list of escape sequences in C can be found in Escape sequences in C.
This won't print % for the second printf.
int main()
{
printf("%%\n");
printf("\%");
printf("\n");
return 0;
}
Output:
%

How do I print the percent sign(%) in C? [duplicate]

This question already has answers here:
How to escape the % (percent) sign in C's printf
(13 answers)
Closed 7 years ago.
Why doesn't this program print the % sign?
#include <stdio.h>
main()
{
printf("%");
getch();
}
Your problem is that you have to change:
printf("%");
to
printf("%%");
Or you could use ASCII code and write:
printf("%c", 37);
:)
There's no explanation in this topic why to print a percentage sign. One must type %% and not for example an escape character with percentage - \%.
From comp.lang.c FAQ list · Question 12.6:
The reason it's tricky to print % signs with printf is that % is
essentially printf's escape character. Whenever printf sees a %, it
expects it to be followed by a character telling it what to do next.
The two-character sequence %% is defined to print a single %.
To understand why % can't work, remember that the backslash \ is the
compiler's escape character, and controls how the compiler interprets
source code characters at compile time. In this case, however, we want
to control how printf interprets its format string at run-time. As far
as the compiler is concerned, the escape sequence % is undefined, and
probably results in a single % character. It would be unlikely for
both the \ and the % to make it through to printf, even if printf were
prepared to treat the \ specially.
So the reason why one must type printf("%%"); to print a single % is that's what is defined in the printf function. % is an escape character of printf's, and \ of the compiler.
Use "%%". The man page describes this requirement:
% A '%' is written. No argument is converted. The complete conversion specification is '%%'.
Try printing out this way
printf("%%");

How to escape the % (percent) sign in C's printf

How do you escape the % sign when using printf in C?
printf("hello\%"); /* not like this */
You can escape it by posting a double '%' like this: %%
Using your example:
printf("hello%%");
Escaping the '%' sign is only for printf. If you do:
char a[5];
strcpy(a, "%%");
printf("This is a's value: %s\n", a);
It will print: This is a's value: %%
As others have said, %% will escape the %.
Note, however, that you should never do this:
char c[100];
char *c2;
...
printf(c); /* OR */
printf(c2);
Whenever you have to print a string, always, always, always print it using
printf("%s", c)
to prevent an embedded % from causing problems (memory violations, segmentation faults, etc.).
If there are no formats in the string, you can use puts (or fputs):
puts("hello%");
if there is a format in the string:
printf("%.2f%%", 53.2);
As noted in the comments, puts appends a \n to the output and fputs does not.
With itself...
printf("hello%%"); /* like this */
Use a double %%:
printf("hello%%");
Nitpick:
You don't really escape the % in the string that specifies the format for the printf() (and scanf()) family of functions.
The %, in the printf() (and scanf()) family of functions, starts a conversion specification. One of the rules for conversion specification states that a % as a conversion specifier (immediately following the % that started the conversion specification) causes a '%' character to be written with no argument converted.
The string really has 2 '%' characters inside (as opposed to escaping characters: "a\bc" is a string with 3 non null characters; "a%%b" is a string with 4 non null characters).
Like this:
printf("hello%%");
//-----------^^ inside printf, use two percent signs together
You can use %%:
printf("100%%");
The result is:
100%
You are using the incorrect format specifier. You should use %% for printing %. Your code should be:
printf("hello%%");
Read more all format specifiers used in C.
The backslash in C is used to escape characters in strings. Strings would not recognize % as a special character, and therefore no escape would be necessary. printf is another matter: use %% to print one %.
You can simply use % twice, that is "%%"
Example:
printf("You gave me 12.3 %% of profit");
Yup, use printf("hello%%"); and it's done.
The double '%' works also in ".Format(…).
Example (with iDrawApertureMask == 87, fCornerRadMask == 0.05):
csCurrentLine.Format("\%ADD%2d%C,%6.4f*\%",iDrawApertureMask,fCornerRadMask) ;
gives the desired and expected value of (string contents in) csCurrentLine;
"%ADD87C, 0.0500*%"

Resources