This Tutorial Discusses the Usage and Examples of <cstdio> Functions like printf, sprintf, scanf that are used for Formating Input/Output in C++:
In our previous C++ tutorials, we have seen that we can perform Input-Output operations in C++ using cin/cout.
Apart from using these constructs, we can also make use of the C library. Using C Standard Input and Output Library (cstdio, C++ equivalent for stdio.h header in C language), we perform I/O operations using “streams” that operate with physical devices like keyboards (standard input), printers, terminals (standard output) or any other file types supported by the operating system.
=> Check The In-Depth C++ Training Tutorials Here.
Streams are nothing but an abstract entity that is used to interact with physical devices in a uniform manner. All the streams have similar characteristics and are independent of the physical media devices.
In our next topics in this tutorial, we will learn in detail about a few <cstdio> functions, i.e. printf, sprint, and scanf.
Table of Contents:
C++ printf
The printf function in C++ is used to write the output that is formatted to stdout.
Function Prototype:
int printf (const char* format, …);
Parameters:
format => A pointer to null-terminated string written to file stream. It consists of characters along with an optional format specifier that begins with %. The format specifier is replaced by appropriate values that follow the format string.
… => Other additional arguments that specify the data to be printed in the order the format is specified.
Return value:
Success => printf returns the number of characters returned.
Failure => Negative value
Description:
The printf function is defined in <cstdio> header. The printf functions write the string pointed to by the “format” pointer to standard output stdout. The format string may contain format specifiers which are then replaced by the variables passed to the printf function as additional arguments (after format string).
Format Specifier Used In printf () Function
A general form of format specifier is
%[flags][width][.precision][length]specifier
Given below is a description of each of the parts of format specifier:
- % sign: This is a leading % sign
- Flags: They can have the following values:
- –: Left justifies the result within the field. By default, right justified.
- +: The sign of the result attached to the beginning of the value including positive results.
- Space: In the absence of a sign, space is attached to the beginning of the result.
- #: Specify an alternative form of conversion.
- 0: Used for integer and floating-point numbers. Act as leading zeros in the absence of space.
- Width: Specifies minimum field width in the form of a * or an integer value. This is optional.
- Precision: Specifies precision with a ‘.’ followed by a * or an integer or nothing. This is also optional.
- Length: The optional argument that specified the size of the argument.
- Specifier: This is a conversion format specifier.
Various Format Specifiers used in C++ are as follows:
No | Specifier | Description |
---|---|---|
1 | % | Prints a %. |
2 | c | Prints single character. |
3 | s | Prints a string. |
4 | d/i | Converts signed integer to decimal representation. |
5 | o | Converts unsigned integer to octal representation. |
6 | x/X | Converts unsigned integer to hexadecimal representation. |
7 | u | Converts unsigned integer to decimal representation. |
8 | f/F | Converts floating-point number to decimal representation. |
9 | e/E | Converts floating-point number to decimal exponent notation. |
10 | a/A | Converts floating-point number to a hexadecimal exponent. |
11 | g/G | Converts floating-point number to decimal or decimal exponent notation. |
12 | n | Number of characters written so far by this function call. |
13 | p | A pointer pointing to Implementation defined character sequence. |
Given below is a complete C++ programming example that demonstrates the printf function discussed above.
C++ printf Example
#include <cstdio> //C++ printf example int main() { char ch = 'A'; float a = 8.0, b = 3.0; double d = 3.142; int x = 20; printf("float division : %.3f / %.3f = %.3f \n", a,b,a/b); printf("Double value: %.4f \n", d); printf("Setting width %*c \n",4,ch); printf("Octal equivalent of %d is %o \n",x,x); printf("Hex equivalent of %d is %x \n",x,x); return 0; }
Output:
The above program uses various calls to the printf function and we note that each call to printf uses various format specifiers we discussed above. The format specifier %.3f denotes a float value with up to 3 decimal places. The rest of the printf calls display the character, decimal, octal and hex values.
C++ sprintf
Sprintf function in C++ similar to printf function except with one difference. Instead of writing the output to standard output stdout, sprintf writes the output to a character string buffer.
Function Prototype:
int sprintf (char* buffer, const char* format, …)
Parameters:
buffer => Pointer to a string buffer to which the result is to be written.
Format=> Pointer to a null-terminated string that is written to file stream.
Note: The format string used in the sprintf function is the same as the one discussed as part of the printf function description.
… => Other additional arguments that specify the data to be printed in the order the format is specified.
Return Value:
success => Returns the number of characters written to the sufficiently large buffer excluding the terminating null character.
Failure => Negative value is returned.
Description:
Sprintf function is defined in the <cstdio> header. The sprintf function is used to write a string pointed by the format to the string buffer. The string format may contain format specifiers starting with % which are replaced by the values of variables that are passed to the sprintf () function as additional arguments.
Let us see an example C++ program that shows the usage of sprintf function.
sprintf Example
#include <cstdio> #include <iostream> using namespace std; int main() { char mybuf[100]; int retVal; char name[] = "Software Testing Help"; char topic[] = "C++ tutorials"; retVal = sprintf(mybuf, "Hi, this is %s and you are reading %s !!", name, topic); cout << mybuf << endl; cout << "Number of characters written = " << retVal << endl; return 0; }
Output:
In the example above, first, we write a formatted string to a character buffer mybuf using the sprintf function. Then we display the string to stdout using cout. Finally, we display the number of characters written to the mybuf buffer.
C++ scanf
The scanf function in C++ reads the input data from standard input stdin.
Function Prototype:
int scanf (const char* format, …)
Parameters:
format => Pointer to a null-terminated string that defines how to read the input. This format string consists of format specifiers.
… => Additional arguments receiving data input. These additional arguments are in sequence according to the format specifier.
Return value:
success=> Returns a number of characters read in.
matchingFailure=> Returns zero if matching failure occurs before the first receiving argument is assigned.
input Failure => Returns EOF if an input failure occurs before the first receiving argument is assigned.
Description:
Scanf() function is defined in the <cstdio> header. This function reads the data from stdin and stores in the variables provided.
Format Specifier Used In scanf() Function
The general format for the scanf () function format string is:
%[*][width][length]specifier
Thus the format specifier has the following parts:
- Non-whitespace character: These are the characters except % that consume one identical character from the input stream.
- Whitespace character: All consecutive whitespace characters are considered as one whitespace character. The same goes for escape sequences too.
- Conversion specification: It has the following format:
- %: Character that specifies the beginning.
- *: Called assignment suppressing character. If present, the scanf does not assign the result to any receiving parameters. This parameter is optional.
- Field width: Optional parameter (a positive integer) that specifies a maximum field width.
- Length: Specifies the size of receiving an argument.
Conversion Format Specifier can be as follows:
No | Format specifier | Description |
---|---|---|
1 | % | Matches literal %. |
2 | c | Matches single character or multiple characters up to width. |
3 | s | Matches sequence of non-whitespace character until specified width or first whitespace. |
4 | d | Matches decimal. |
5 | i | Matches integer. |
6 | o | Matches unsigned octal integer. |
7 | x/X | Matches unsigned hexadecimal integer. |
8 | u | Matches unsigned decimal integer. |
9 | a/A, e/E,f/F, g/G | Matches floating-point number. |
10 | [set] | Matches non-.empty sequence of characters from the given set. If preceded by ^, then characters not in set are matched. |
12 | n | Returns number of characters read so far. |
13 | p | Pointer to implementation specific character sequence. |
Next, we will implement a sample program to demonstrate the usage of scanf function in C++
scanf Example
#include <cstdio> int main () { char str [80], pos_str[80]; int i; printf ("Enter your company name: "); scanf ("%79s",str); printf ("Enter your position: "); scanf ("%s",pos_str); printf ("You work at %s as %s.\n",str,pos_str); printf ("Enter a hexadecimal number: "); scanf ("%x",&i); printf ("You have entered %#x (%d).\n",i,i); return 0; }
Output:
In the above program, we read two input strings and a hexadecimal number. Then we combine the two strings and display the resultant string. The number is converted to decimal and displayed.
scanf/printf Vs. cin/cout In C++
scanf/printf | cin/cout |
---|---|
Standard input-output in C language. | Standard input-output in C++ language. |
Defined in 'stdio.h'. | Defined in 'iostream'. |
scanf and printf are a function used for I/O. | cin and cout are stream objects. |
The format string is used for formatting the input and output. | Operators >> and << are overloaded and used along with cin and cout respectively. No format string is used. |
We specify the type of data using place holder. | No need to specify the data type. |
Frequently Asked Questions
Q #1) Can you use printf in C++?
Answer: Yes. Printf can be used in C++. To use this function in a C++ program, we need to include the header <cstdio> in the program.
Q #2) What language uses printf?
Answer: Printf is the standard output function in C language. It can also be used in C++ language by including the header <cstdio> in C++ program.
Q #3) What is %d in C programming?
Answer: %d value in printf function refers to an integer value.
Q #4) Why & is used in Scanf?
Answer: & operator is used to access the memory location. It is shorthand to pass a pointer to the variable instead of passing it explicitly.
Q #5) What is the difference between printf () and sprintf ()?
Answer: Both the functions printf() and sprintf() are same except for one difference. While printf() writes the output to stdout (standard output), the sprintf writes the output to a character string buffer.
Q #6) Does Sprintf null terminate?
Answer: sprintf returns the number of characters stored in character string array excluding the null termination character.
Q #7) Why is sprintf unsafe?
Answer: Sprintf function does not check the length of the destination buffer. Hence when the length of the format string is too long, the function might cause the overflow of the destination buffer. This may lead to application instability and security issues thereby making sprintf function unsafe.
Conclusion
In this tutorial, we have learned the C library input-output functions – printf, sprintf, and scanf that can be used in C++ by including the header <cstdio> which is the equivalent for C header <stdio.h>.
As already discussed, the input-output functions in <cstdio> use format specifiers and place holders and we need to specify the data types of variables in which data is read or written to.
Contrary to this, the streaming objects used in C++ – cin, and cout do not use any format specifiers or placeholders. They use overloaded >> and << operators to read in and write the data.
=> Check Out The Perfect C++ Training Guide Here.