The printf and scanf functions are the most popular input and output functions in C language. Both functions are inbuilt library functions which is part of stdio.h header file. Before using both functions in our program, we must include stdio.h header file as shown below.
printf Function in C
The printf function of stdio C Library writes a formatted string to stdout. If format contains format specifiers (subsequences beginning with %), the additional arguments following format are inserted after formatting in the resulting string by replacing their respective format specifiers.
Syntax of printf functionprintf("format string", arg1, arg2, ...);
- format string : A string that contains format specifiers. These specifiers indicate the type and format of the data to be printed.
- arg1, arg2, ... : The values to be printed, corresponding to the format specifiers in the format string.
Format Specifiers
Here are some commonly used format specifiers in printf():- %d : Integer
- %f : Floating-point number
- %c : Character
- %s : String
- %x : Hexadecimal (integer)
- %p : Pointer
- %% : Percent sign
Width and Precision
You can control the width and precision of the output by specifying numerical values in the format specifiers. For example:
#include <stdio.h> int main() { float pi = 3.14159; // Printing with width and precision printf("Pi with 2 decimal places: %.2f\n", pi); printf("Pi with width 10 and 3 decimal places: %10.3f\n", pi); return 0; }In the above example, %.2f prints the floating-point number with two decimal places, and %10.3f prints the number with a width of 10 characters and three decimal places.
Escape Sequences
printf() also supports escape sequences for special characters:- \n : Newline
- \t : Tab
- \" : Double quote
- \' : Single quote
- \\ : Backslash
#include <stdio.h> int main() { // Using escape sequences printf("This is a newline.\n"); printf("This is a tab.\tAnd this is a backslash: \\.\n"); return 0; }
C program to print formatted strings using printf
The following program shows the use of printf function to print a formatted literals on screen.#include <stdio.h> int main(){ printf("Printing characters\n"); printf("%c %c %c %c\n\n", 'a', 'A', '#', '1'); printf("Printing integers\n"); printf("%d %ld %10d %010d\n\n", 2015, 2015L, 2015, 2015); printf("Printing floating point numbers\n"); printf("%f %5.2f %+.0e %E\n\n", 1.41412, 1.41412, 1.41412, 1.41412); printf("Printing string\n"); printf("%s\n\n", "TechCrashCourse"); printf("Printing radicals\n"); printf ("%d %x %o %#x %#o\n\n", 2105, 2015, 2015, 2015, 2015); return 0; }Output
Printing characters a A # 1 Printing integers 2015 2015 2015 0000002015 Printing floating point numbers 1.414120 1.41 +1e+000 1.414120E+000 Printing string TechCrashCourse Printing radicals 2105 7df 3737 0x7df 03737
scanf Function in C
The scanf function of stdio C Library function reads formatted data from stdin and stores them in the variables pointed by the additional arguments. Additional arguments must point to variables of the same type as specified in the format.
Format is a null terminated string that contains Whitespace character, Non-whitespace character and Format specifiers.
int scanf(const char *format, ...);
C program to take input from user using scanf function
The following program shows the use of scanf function to read formatted data from a stdin.#include <stdio.h> int main(){ int a, b, sum; printf("Enter to integers to add\n"); /* Taking input from user using scanf */ scanf("%d %d", &a, &b); sum = a + b; printf("%d + %d = %d", a, b, sum); return 0; }Output
Enter to integers to add 3 9 3 + 9 = 12
Format Specifiers for scanf()
Here are some commonly used format specifiers in scanf().
- %d : Integer
- %f : Floating-point number
- %c : Character
- %s : String
- Reading Multiple Values : To read multiple values, you can use multiple format specifiers in a single scanf() call:
#include <stdio.h> int main() { int num1, num2; printf("Enter two numbers separated by a space: "); scanf("%d %d", &num1, &num2); printf("You entered: %d and %d.\n", num1, num2); return 0; }
- Ignoring Characters : To disregard specific values, incorporate the asterisk (*) into format specifiers.
#include <stdio.h> int main() { int num1, num2; printf("Enter two numbers separated by a comma: "); scanf("%d, %d", &num1, &num2); printf("You entered: %d and %d.\n", num1, num2); return 0; }
The comma in the format specifier%d,%d enables scanf() to disregard the comma while reading the input in this instance. - Buffer Flushing : It is critical to acknowledge that potential complications may arise with the input buffer when combining scanf() with other input functions. To address this, clean the input buffer using getchar() or fflush(stdin):
#include <stdio.h> int main() { int num; char character; printf("Enter a number: "); scanf("%d", &num); // Flush the buffer getchar(); printf("Enter a character: "); scanf("%c", &character); printf("You entered: %d and %c.\n", num, character); return 0; }
Error Handling
Checking scanf() Return Value
The scanf() function returns the count of items that were input successfully. It outputs EOF (End of File) in the event of an input failure.
#include <stdio.h> int main() { int num; // Reading the input and checking for errors if (scanf("%d", &num) == 1) { printf("You entered: %d.\n", num); } else { printf("Invalid input.\n"); } return 0; }In this example, the program checks if scanf() successfully read one item (in this case, an integer).
Conclusion
During this tutorial, we examined the printf() and scanf() functions in C, which are fundamental tools for manipulating input and output. We discussed the fundamental syntax of these functions, including format specifiers and usage examples. Comprehending the concepts of output formatting and input reading is essential in the development of interactive and user-centric C programs.
Bear in mind, as you progress through the C programming language, the critical nature of error handling, particularly when user input is involved. Obtaining proficiency in printf() and scanf() is critical for developing interactive applications or command-line utilities in C. Mastering these functions is equivalent to attaining expertise in interactive programming.