![]() |
VOOZH | about |
In C, there are many input and output for different situations, but the most commonly used functions for Input/Output are scanf() and printf() respectively. These functions are part of the standard input/output library <stdio.h>. scanf() takes user inputs (typed using keyboard) and printf() displays output on the console or screen.
The printf() function is used to print formatted output to the standard output stdout (which is generally the console screen). It is one of the most commonly used functions in C.
The following examples demonstrate the use of printf for output in different cases:
First Print
Explanation: The text inside "" is called a string in C. It is used to represent textual information. We can directly pass strings to the printf() function to print them in console screen.
22
Here, the value of variable age is printed. You may have noticed %d in the formatted string. It is actually called format specifier which are used as placeholders for the value in the formatted string.
You may have also noticed '\n' character. This character is an escape sequence and is used to enter a newline.
The value of the variable age is 22
The printf function in C allows us to format the output string to console. This type of string is called formatted string as it allows us to format (change the layout the article).
The fputs() function is used to output strings to the files but we can also use it to print strings to the console screen.
This is my string
scanf() is used to read user input from the console. It takes the format string and the addresses of the variables where the input will be stored.
Remember that this function takes the address of the arguments where the read value is to be stored.
The following examples demonstrate how to use the scanf for different user input in C:
Output
Enter your age:
25 (Entered by the user)
Age is: 25
Explanation: %d is used to read an integer, and &age provides the address of the variable where the input will be stored.
Output
Enter a character:
a (Entered by the user)
Entered character is: a
The scanf() function can also be used to read string input from users. But it can only read single words.
Output:
Enter a String:
Geeks (Entered by the user)
Entered string is: Geeks
The scanf() function with %s stops at the first whitespace and does not read spaces. To handle this, we can use fgets(), which can read spaces and is safer because it limits the number of characters read, helping prevent buffer overflow.
fgets() reads the given number of characters of a line from the input and stores it into the specified string. It can read multiple words at a time.
Output
Enter your name:
John(Entered by User)
Hello, John
For reading a single character, we use getchar() in C.