Computer Science

C Printf

C printf is a function in the C programming language used to print formatted output. It allows for the insertion of variables and control over the formatting of the output, such as specifying the number of decimal places for floating-point numbers or padding strings with spaces. The printf function is a fundamental tool for displaying information in C programs.

Written by Perlego with AI-assistance

9 Key excerpts on "C Printf"

  • Book cover image for: Key dynamics in computer programming
    • Adele Kuzmiakova(Author)
    • 2023(Publication Date)
    • Arcler Press
      (Publisher)
    It uses several formatting operators and conversion specifiers to combine numerical values of any type into a character string (Figure 5.9) (Joseph, 2018). Figure 5.9. Display (printf) code in C. Source: https://www.getfreeebooks.com/an-introduction-to-the-c-program- ming-language-and-software-design/. • Important: A conversion specifier and the variable it refers to must be of the same type. If they are not, the software will either crash or output junk. printf(“percent f,” 52); / is an example. * Integer value with floating-point specifier */ Fundamentals of C Programming 147 REFERENCES 1. Alturki, M. A., (2017). A symbolic rewriting semantics of the COMPASS modeling language. In: 2017 IEEE International Conference on Information Reuse and Integration (IRI) (pp. 283–290). IEEE. 2. Ambriola, V., Giannotti, F., Pedreschi, D., & Turini, F., (1985). Symbolic semantics and program reduction. IEEE Transactions on Software Engineering, (8), 784–794. 3. Austin, T. M., Breach, S. E., & Sohi, G. S., (1994). Efficient detection of all pointer and array access errors. In: Proceedings of the ACM SIGPLAN 1994 conference on Programming Language Design and Implementation (pp. 290–301). 4. Backus, D. J. (2003). 2.9. 1 Obsolescence and Deletions 2.9. 2” Hello World” Example 2.10 Fortran 95 2.10. 1 Conditional Compilation and Varying Length Strings 2.11 Fortran 2003 (Vol. 3). 5. Ball, T., & Rajamani, S. K., (2001). Automatically validating temporal safety properties of interfaces. In: International SPIN Workshop on Model Checking of Software (pp. 102–122). Springer, Berlin, Heidelberg. 6. Boudjema, E. H., Faure, C., Sassolas, M., & Mokdad, L., (2018). Detection of security vulnerabilities in C language applications. Security and Privacy, 1(1), e8. 7. Brooks, D. R., (1999). The basics of C programming. In: C Programming: The Essentials for Engineers and Scientists (pp. 23– 69). Springer, New York, NY. 8. Bryant, R. E., Lahiri, S.
  • Book cover image for: Introduction to Embedded Systems
    eBook - PDF

    Introduction to Embedded Systems

    Using ANSI C and the Arduino Development Environment

    • David Russell(Author)
    • 2022(Publication Date)
    • Springer
      (Publisher)
    2.2, main() has only one statement, a function call to printf() with a single argument, the address of a string of bytes. The function printf() was not written by us; it is a library function that is defined in the header file stdio.h, and ultimately linked in by the linker. Hence, there must be an object library or object file somewhere that contains the object code for printf(). 26 2. ANSI C 2.3 FORMATTED OUTPUT Often in embedded environments, we have to rely completely on printf() in order to look at variable values, which is a fundamental component in the debugging process. The fprintf() function provides formatted output conversion. Example 2.4 int int int fprintf (FILE *stream , const const const char char char *format , ...) This function converts and writes output to stream under the control of format. The return value is the number of characters written, or negative if an error occurred. The format string contains two types of objects. 1. Ordinary characters, which are copied to the output stream, and 2. conversion specifications, each of which causes conversion and printing of the next successive argument to fprintf(). Each conversion specification begins with the character % and ends with a conversion character. Between the % and the conversion character there may be, in the following order : • Flags (in any order), which modify the specification, are listed in Table 2.1. Table 2.1: Formatted Printing Conversion Specification Flags Flag Modification - specifies left adjustment of the converted argument in its field + specifies that the number will always be printed with a sign space if the first character is not a sign, a space will be prefixed 0 for numeric conversion, specifies padding to the field width with leading zeros # specifies an alternative output form (e.g., for x, 0x will be prefixed to a non-zero result) • A number specifying a minimum field width. The converted argument will be printed in a field at least this wide, and wider if necessary.
  • Book cover image for: Buffer Overflow Attacks
    eBook - PDF

    Buffer Overflow Attacks

    Detect, Exploit, Prevent

    • Jason Deckard(Author)
    • 2005(Publication Date)
    • Syngress
      (Publisher)
    These functions allow a programmer to create a string based on a format string and a variable number of arguments.The format string can be considered a blueprint containing the basic structure of the string and tokens that tell the printf function what kinds of variable data goes where, and how it should be formatted.The printf tokens are also known as format specifiers; the two terms are used interchangeably in this chapter. Table 7.1 describes a list of the standard printf functions included in the standard C library and their prototypes. Table 7.1 The printf() Family of Functions Function Description printf(char *, ...); This function allows a formatted string to be created and written to the standard out I/O stream. Figure 7.2 Incorrect Stack Operation with va_args Continued Format Strings Attacks • Chapter 7 279 Table 7.1 The printf() Family of Functions Function Description fprintf(FILE *, char *, ...); This function allows a formatted string to be created and written to a libc FILE I/O stream. sprintf(char *, char *, ...); This function allows a formatted string to be created and written to a location in memory. Misuse of this function often leads to buffer over-flow conditions. snprintf(char *, size_t, char *, ...); This function allows a formatted string to be created and written to a location in memory, with a max-imum string size. In the context of buffer overflows, it is known as a secure replacement for sprintf(). The standard C library also includes the vprintf(), vfprintf(), vsprintf(), and vsnprintf() functions.These perform the same functions as their counterparts listed previously, but they accept varargs (variable arguments) structures as their arguments. Instead of the whole set of arguments pushed on the stack, only the pointer to the list of arguments is passed to the function.
  • Book cover image for: Basic Data Structures and Program Statements
    • Xingni Zhou, Qiguang Miao, Lei Feng(Authors)
    • 2020(Publication Date)
    • De Gruyter
      (Publisher)
    4.2.3 Formatted output function 4.2.3.1 Syntax and signature of formatted output function Let us look at a formatted output function that can output efficiently: the printf function. There are several parameters inside parentheses. Its function signature and functionality are given in Figure 4.11. We shall cover the usage of printf through examples and introduce its rules after that. Signature printf (format control sequence, parameter 1,…,parameter n) Functionality Output values of parameter 1 to parameter n to standard output devices in format specified by “format control sequence”. Parameters are expressions. Formatted output function Figure 4.11: Formatted output function. 146 4 Input/output Example 4.4 Formatted output example: format coordination Variable definitions and output cases are shown in Figure 4.12. Suppose int a=12, b=56; float x=10.8; Output case 2 printf(“%d %d”, a, b ); Format control sequence Argument Output %d□%d a,b 12□56 Output case 1 printf(“%d ”, a); Format control sequence Argument Output %d a 12 We use squares to represent spaces for clearer demonstration Output case 4 printf(%d+%d =%dn, a, b, a+b ); Format control sequence Argument Output %d+%d =%d n a, b, a+b 12+56=68 Output case 3 printf(“%d %f”, a, x); Format control sequence Argument Output %d□□%f a,x 12□□10.8 Rule n is an escape character that represents newline. It is output as defined in grammar. (replaced with arguments) and escape characters (output as defined in grammar) specifiers and arguments Figure 4.12: Formatted output example: format coordination. [Analysis] In output case 1, we print the value of an integer variable a . The format control sequence is the content wrapped by double quotation marks, where %d means that the data will be output as integers. The argument of this function is a , so 12 is output by printf . In case 2, we print values of a and b , which are both integer variables.
  • Book cover image for: C
    eBook - ePub

    C

    From Theory to Practice, Second Edition

    • George S. Tselikis, Nikolaos D. Tselikas(Authors)
    • 2017(Publication Date)
    • CRC Press
      (Publisher)
    printf() returns the number of characters printed or a negative value if an error occurs. For example, consider the following program:
    #include <stdio.h> int main(void ) { printf("%d\n", printf("Test\n")); return 0; }
    Although functions are discussed in Chapter 11 , you should be able to get a sense of what this program is doing. The inner printf() is executed first, it displays Test and returns the number of the characters printed, that is, 5 (as said, \n is counted as one character). The outer printf() uses the %d specifier to display the return value of the inner printf() . Therefore, the program displays:
    Test 5

    Printing Variables

    Variable names follow the last double quote of the format string. When printing more than one variable, separate each with a comma. The compiler will associate the conversion specifications with the names of each of the variables from left to right. Each conversion specification should match the type of the respective variable or the output will be meaningless. Take a look at the following program:
    #include <stdio.h> int main(void ) { int a = 10, b = 20; printf("%d + %d = %d\n", a, b, a+b); printf("%f\n", a); return 0; }
    In the first printf() , the compiler replaces the first %d with the value of a , the second %d with the value of b , and the third one with their sum. Therefore, the program displays: 10 + 20 = 30 . The second printf() displays a meaningless value, since a wrong conversion specification is used.
    The compiler does not check if the number of the conversion specifications equals the number of the variables. If the conversion specifications are more than variables, the program will display meaningless values for any extra specifications. If it is less, the program will not display the values of the extra variables. For example:
    #include <stdio.h> int main(void ) { int a = 10, b = 20; printf("%d and %d and %d\n", a, b); printf("%d\n", a, b); return 0; }
    The first printf() uses the %d specifier three times, although there are only two output variables. The compiler replaces the first %d with the value of a , the second with the value of b , and the third with a meaningless value. Therefore, the program displays: 10 and 20 and some meaningless value. The second printf() uses the %d specifier once, while there are two output variables. The compiler replaces the %d with the value of a and ignores the second variable. Therefore, the program displays 10
  • Book cover image for: Assembly Language Step-by-Step
    eBook - ePub

    Assembly Language Step-by-Step

    Programming with Linux

    • Jeff Duntemann(Author)
    • 2011(Publication Date)
    • Wiley
      (Publisher)
    With puts() we can only send a simple text string to a file (by default, stdout), without any sort of formatting. Worse, puts() always includes an EOL character at the end of its display, whether we include one in the string data or not. This prevents us from using multiple calls to puts() to output several text strings all on the same line. About the best you can say for puts() is that it has the virtue of simplicity. For nearly all character output needs, you're way better off using a much more powerful library function called printf(). The printf() function enables us to do a number of truly useful things, all with one function call: Output text either with or without a terminating EOL Convert numeric data to text in numerous formats, by outputting formatting codes along with the data Output text to a file that includes multiple strings stored separately If you've worked with C for more than half an hour, printf() will be perfectly obvious to you, but for people coming from other languages (such as Pascal, which has no direct equivalent), it may take a little explaining. The printf() routine will gladly display a simple string like “Eat at Joe's!”—but we can merge other text strings and converted numeric data with that base string as it travels toward standard output, and show it all seamlessly together. This is done by dropping formatting codes into the base string, and then passing a data item to printf() for each of those formatting codes, along with the base string. A formatting code begins with a percent sign and includes information relating to the type and size of the data item being merged with the base string, as well as how that information should be presented. Let's look at a very simple example to start out
  • Book cover image for: Computer Fundamentals - 8th Edition
    eBook - ePub

    Computer Fundamentals - 8th Edition

    Concepts, Systems & Applications

    • Pradeep K.Sinha, Pradeep K.Sinha, Priti Sinha(Authors)
    • 2004(Publication Date)
    • BPB Publications
      (Publisher)
    printf() to get the output split over separate lines.
    gets()
    Enables input of a string from keyboard. Spaces are accepted as part of the input string, and the input string is terminated when Enter key is hit. Note that although scanf() enables input of a string of characters, it does not accept multi-word strings (spaces in-between).
    puts() Enables output of a multi-word string
    Figure 21.6. Basic library functions for performing simple I/O operations in C.
    Figure 21.7 lists the format specifiers for scanf() and printf() along with their corresponding data types.
    Format specifiers Data types
    %d integer (short signed)
    %u integer (short unsigned)
    %ld integer (long signed)
    %lu integer (long unsigned)
    %f real (float)
    %lf real (double)
    %c character
    %s string
    Figure 21.7. Basic format specifiers for scanf() and printf().
    Examples:

    PREPROCESSOR DIRECTIVES

    The example above used the library functions clrscr() , printf() , and scanf() . These are library functions for input/output. Every C compiler provides many such useful library functions that programmers can use directly in their programs. Compilers group the library functions in different categories and store them in different files. For example, library functions for I/O are stored in “stdio.h” file, and library functions for string handling are stored in “string.h” file.
    To use one or more library function from a standard file of library functions in a program, the code of that function should be included in the program so that the compiler generates the object code for the instructions in the library function as well. To enable this, C provides “#include ” preprocessor directive that tells the C preprocessor to look for a file and place the contents of the file in that location of the program where #include directive is used. The preprocessor
  • Book cover image for: Basic Computation and Programming with C
    10. The output will be 5.000000. %f is the format specifier used in printf function to display any data of float type. Here the float variable i contains 5. So it has been displayed as 5.000000. Note 6 digits are taken after the decimal point which is the default behavior in C in case of floating point data. C has the provision to restrict the number of digits after decimal point. 5 and 5.0 are different. One is integer and the other is float. Format specifier %f is used for float, and %d is used for int. So replacing %d in place of %f will generate the output 5. 11. The statement putchar(‘n’) is valid. n is the newline character. Here n is treated as a single character. putchar( ) function can display a single character. So the statement putchar(‘n’); will print a new line character. In putchar(‘n’) statement, will be interpreted as only and n will become n. This is not the new line character any more but two consecutive characters and n. Since putchar can accept only one character, this statement is invalid. 12. The function getchar( ) is used to accept a single character from the keyboard. The function getchar( ) accepts a single character and stores it in a variable. The syntax for writing getchar( ) is: variable = getchar(); 13. The output will be 3.46. Here in the control string, the format specifier “%.2f” means some float value will be displayed and after the decimal point, only two digits will be taken even if the original data contains more digits. So the digit 2 indicates the width of the digits after decimal point. But during the truncation process it will check the third digit. If it is 5 or greater than 5, then 1 will be added with the second digit. Here the third digit after the decimal point is 6 which is greater than 5, so 1 will be added with the second digit and the final output will be 3.46. 14. The output will be 50. The content of the character variable c is character 2. All characters are represented with their ASCII value.
  • Book cover image for: Computer Programming with C++
    5 6 Figure 2.28: Output of printf(%8.2f,y); Fundamentals ✦ 49 only specifies the width as 20 but no precision, in this case, the full number will be printed in right justified form (leaving first 11 spaces blank) as shown in Figure 2.31. Output width of 20 spaces 11 blank spaces in the beginning Full number in right justified form 3 5 4 6 5 . 0 0 1 Figure 2.31: Output of printf(%20f,y); 2.7 C++ Style of Printing the Value on Computer Screen Recall, cout statement is supported by C++ (not by C) to print a message on the computer screen. Along with the text message, we can also print the value of a particular variable using a cout statement in a C++ program. The only difference between printing a text message and the value of a variable is that the text message to be printed must always be surrounded in double quotes whereas if we wish to print the value of a variable using a cout statement then the variable name must be written without double quotes. This facilitates the C++ compiler to differentiate between the parts of the cout statement which represents the direct text message to be printed on the screen and the parts of the cout statement which represent the variable name(s) whose values are to be printed on the computer screen. Given below is the syntax to print the value of the N variables defined in the C++ program using a single cout statement: cout<
Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.