0

Why do we need format specifiers in C language?

23rd Jun 2019, 5:06 PM
Shakti Singh
5 odpowiedzi
+ 10
• Printing Out and Inputting Variables C uses formatted output. The 'printf' function has a special formatting character (%) — a character following this defines a certain format for a variable:   %c — characters   %d — integers   %f  — floats     printf("%c %d %f", ch, i, x); NOTE: Format statement enclosed in "..." , variables follow after. Make sure order of format and variable data types match up. scanf() is the function for inputting values to a data structure. Its format is similar to 'printf' :     scanf("%c %d %f", &ch, &i, &x); NOTE: & before variables. Here is an example, • https://code.sololearn.com/cbvUE5gzIv4q/?ref=app
23rd Jun 2019, 8:06 PM
Danijel Ivanović
Danijel Ivanović - avatar
+ 2
because each representation of data are different, integers, characters, hexadecimal, floating point etc.
23rd Jun 2019, 5:47 PM
✳AsterisK✳
✳AsterisK✳ - avatar
+ 1
Because that's the way input and output stream functions would "interpret" what type of variables they're going to be dealing with. For instance, an integer argument needs a `%d` specifier to format correctly the produced string of a `printf()` statement. Using the wrong specifier, for example, `%f` in above situation leads to undefined behavior. Example: int main(void) { char c; int n, m; double d1, d2; scanf("%c", &c); /* OK */ scanf("%d", &n); /* OK */ scanf("%lf", &d1); /* OK */ printf("%c\n", c); /* OK */ printf("%d\n", n); /* OK */ printf("%f\n", d1); /* OK */ scanf("%c", &m); /* UB */ scanf("%f", &d2); /* UB */ printf("%d\n", m); /* The content of m is undefined */ printf("%f\n", d2); /* The content of d2 is undefined */ } Inputs: c 4 3.14 254 2.5002 Outputs: c 4 3.140000 10 0.000000 Live demo: https://rextester.com/ZMNW93858
23rd Jun 2019, 6:04 PM
To Seek Glory in Battle is Glorious
To Seek Glory in Battle is Glorious - avatar
0
Format specifiers in C. Format specifier is used during input and output. It is a way to tell the compiler what type of data is in a variable during taking input using scanf() or printing using printf(). Some examples are %c, %d, %f, etc.
23rd Jun 2019, 5:53 PM
Anil
Anil - avatar