fprintf , _fprintf_l , fwprintf , _fwprintf_l
locale
Используемый языковой стандарт.
Возвращаемое значение
fprintf возвращает число записанных байтов. fwprintf возвращает число записанных расширенных символов. В случае ошибки вывода каждая из этих функций возвращает отрицательное значение. Если stream или format имеет значение NULL , эти функции вызывают обработчик недопустимых параметров, как описано в разделе Проверка параметров. Если продолжение выполнения разрешено, функции возвращают значение -1 и задают для errno значение EINVAL . Строка формата не проверяется на допустимость символов форматирования, как при использовании fprintf_s или fwprintf_s .
Дополнительные сведения о кодах возврата см. в разделе errno , _doserrno , _sys_errlist и _sys_nerr .
Комментарии
Функция fprintf форматирует и выводит набор символов и значений в выходной поток stream . Каждый argument функции (при наличии) преобразуется и выводится согласно соответствующей спецификации формата в format . Для fprintf аргумент имеет format тот же синтаксис, что и в printf .
fwprintf — версия функции fprintf для расширенных символов; в функции fwprintf параметр format — это строка расширенных символов. Эти функции ведут себя одинаково, если поток открыт в режиме ANSI. Функция fprintf на данный момент не поддерживает вывод данных в поток в кодировке Юникод.
Версии этих функций с суффиксом _l идентичны за исключением того, что они используют переданный параметр языкового стандарта вместо языкового стандарта текущего потока.
Убедитесь, что format не является строкой, определяемой пользователем.
Начиная с Windows 10 версии 2004 (сборка 19041) printf семейство функций печатает точно представленные числа с плавающей запятой в соответствии с правилами округления IEEE 754. В предыдущих версиях Windows точно представленные числа с плавающей запятой, заканчивающиеся на «5», всегда округлялись вверх. IEEE 754 гласит, что они должны округлиться до ближайшей четной цифры (также известный как «Округление банкира»). Например, и printf(«%1.0f», 1.5) printf(«%1.0f», 2.5) должны округлиться до 2. Ранее значение 1,5 округлялось до 2, а 2,5 округлялось до 3. Это изменение влияет только на точно представленные числа. Например, значение 2,35 (которое при представлении в памяти ближе к 2,350000000000000008) продолжает округление до 2,4. Округление, выполняемое этими функциями, теперь также учитывает режим округления с плавающей запятой, заданный параметром fesetround . Ранее округление всегда выбирало FE_TONEAREST поведение. Это изменение затрагивает только программы, созданные с помощью Visual Studio 2019 версии 16.2 и более поздних версий. Чтобы использовать устаревшее поведение округления с плавающей запятой, свяжите с legacy_stdio_float_rounding.obj.
Сопоставления подпрограмм универсального текста
TCHAR.H Обычной | _UNICODE и _MBCS не определены | _MBCS Определенные | _UNICODE Определенные |
---|---|---|---|
_ftprintf | fprintf | fprintf | fwprintf |
_ftprintf_l | _fprintf_l | _fprintf_l | _fwprintf_l |
Дополнительные сведения см. в разделе Синтаксис спецификации формата.
Требования
Компонент | Обязательный заголовок |
---|---|
fprintf , _fprintf_l | |
fwprintf , _fwprintf_l | или |
Дополнительные сведения о совместимости см. в разделе Compatibility.
Пример
// crt_fprintf.c /* This program uses fprintf to format various * data and print it to the file named FPRINTF.OUT. It * then displays FPRINTF.OUT on the screen using the system * function to invoke the operating-system TYPE command. */ #include #include FILE *stream; int main( void )
this is a string 10 1.500000
C++ printf: Printing Formatted Output To Console Or File
In C++, printf is a standard library function that is used to print formatted output to the console or a file.
Important disclosure: we’re proud affiliates of some tools mentioned in this guide. If you click an affiliate link and subsequently make a purchase, we will earn a small commission at no additional cost to you (you pay nothing extra). For more information, read our affiliate disclosure.
Format Specifiers
In printf , format specifiers are used to define the type and format of the data to be printed. They are placeholders that are replaced by the corresponding values passed as arguments to the function. The most commonly used format specifiers in printf are:
- %d — integer
- %f — floating-point number
- %s — string
- %c — character
- %p — pointer address
- %x — hexadecimal integer
- %o — octal integer
For example, to print an integer value using printf , we can use the %d format specifier as follows:
int num = 10; printf("The value of num is: %d\n", num);
This will print the value of num as 10 on the console.
Similarly, to print a floating-point number, we can use the %f format specifier:
float fnum = 3.14159; printf("The value of fnum is: %f\n", fnum);
This will print the value of fnum as 3.14159 on the console.
Format specifiers can also be combined with other options to control the precision, width, and alignment of the output. For example, we can use the %6.2f format specifier to print a floating-point number with a width of 6 characters and a precision of 2 decimal places:
float fnum = 3.14159; printf("The value of fnum is: %6.2f\n", fnum);
This will print the value of fnum as 3.14 (note the two spaces before the number) on the console.
Escape Sequences
In printf , escape sequences are special characters that are used to represent non-printable characters or to control the format of the output. They are represented by a backslash ( \ ) followed by a character or a combination of characters. Some of the commonly used escape sequences in printf are:
- \n — newline
- \t — tab
- \\ — backslash
- \» — double quote
- \’ — single quote
- \a — alert (generates a beep sound)
- \b — backspace
- \r — carriage return
- \f — form feed
- \v — vertical tab
For example, to print a string with a newline character at the end, we can use the \n escape sequence as follows:
This will print the string «Hello, world!» on one line and then move the cursor to the beginning of the next line.
Similarly, to print a tab-separated list of values, we can use the \t escape sequence as follows:
printf("Name\tAge\tCity\n"); printf("John\t25\tNew York\n"); printf("Jane\t30\tSan Francisco\n");
This will print a table with three columns, separated by tabs, on the console.
Escape sequences can also be combined with format specifiers to produce complex output formats. For example, we can use the \t escape sequence with the %6.2f format specifier to print a table of floating-point numbers with a width of 6 characters and a precision of 2 decimal places:
printf("Number\tSquare\tCube\n"); for (float x = 1.0; x
This will print a table of numbers, squares, and cubes, separated by tabs and formatted with a width of 6 characters and a precision of 2 decimal places.
Examples Of Printf
Here are some examples of using printf in C++ to print different types of data:
int num = 10; printf("The value of num is: %d\n", num);
This will print the value of num as 10 on the console.
2. Printing floating-point numbers:
float fnum = 3.14159; printf("The value of fnum is: %f\n", fnum);
This will print the value of fnum as 3.141590 on the console.
3. Printing strings:
char str[] = "Hello, world!"; printf("The message is: %s\n", str);
This will print the string «Hello, world!» on the console.
4. Printing characters:
char ch = 'A'; printf("The character is: %c\n", ch);
This will print the character ‘A’ on the console.
5. Printing pointers:
int num = 10; int* ptr = # printf("The pointer address is: %p\n", ptr);
This will print the memory address of num on the console.
6. Using precision and width options:
float fnum = 3.14159; printf("The value of fnum is: %6.2f\n", fnum);
This will print the value of fnum as 3.14 (note the two spaces before the number) on the console, with a width of 6 characters and a precision of 2 decimal places.
7. Using conditional statements and loops:
This will print the numbers 1 to 10 and their parity (even or odd) on separate lines on the console.
Differences Between Printf And Cout
printf and cout are both used to print output to the console in C++. However, they differ in several aspects, including their syntax, features, and performance. Here are some of the key differences between printf and cout :
- Syntax: The syntax of printf is different from that of cout . In printf , the format string and the arguments are passed as separate parameters, whereas in cout , the values are inserted directly into the output stream using the
// using printf printf("The value of num is: %d\n", num); // using cout cout
2. Format specifiers: printf uses format specifiers to control the format of the output, whereas cout uses formatting manipulators. Format specifiers are more powerful and flexible than formatting manipulators, but they can also be more complex and error-prone. For example:
// using printf printf("The value of fnum is: %6.2f\n", fnum); // using cout cout
3. Performance: printf is generally faster than cout , especially when printing large amounts of data or when formatting the output in a complex way. This is because printf uses a buffer to store the formatted output before writing it to the console, whereas cout writes each value directly to the console. However, the difference in performance is usually small and may not be noticeable in most cases.
4. Portability: printf is part of the C standard library and is therefore more portable than cout , which is part of the C++ standard library. This means that printf can be used in both C and C++ programs, whereas cout is only available in C++.
5. Error handling: printf does not provide any built-in error handling mechanism, whereas cout can throw exceptions in case of errors, such as I/O errors or format errors.
Both printf and cout have their strengths and weaknesses, and the choice of which one to use depends on the specific requirements of the program. In general, printf is more suitable for advanced formatting and high-performance output, whereas cout is more suitable for simple and readable output.
Tips And Tricks
Here are some tips and tricks for using printf effectively and efficiently in C++ programming:
- Use macros: Macros are preprocessor directives that can simplify the use of printf by defining custom format strings and specifiers. For example:
#define LOG(fmt, . ) printf("[%s:%d] " fmt "\n", __FILE__, __LINE__, ##__VA_ARGS__) LOG("The value of num is: %d", num);
This will print the message "[/path/to/file.cpp:10] The value of num is: 10" on the console, with the file name and line number included in the output.
2. Define custom format specifiers: Custom format specifiers can be defined using the %n$ syntax, where n is the argument index. This can simplify the use of printf when dealing with complex data structures. For example:
struct Point < int x; int y; >; printf("The point is: (%1$d, %2$d)\n", pt.x, pt.y);
This will print the coordinates of the point in the format (x, y) on the console.
3. Avoid buffer overflows: Buffer overflows can occur when the size of the output exceeds the size of the buffer used by printf . To avoid buffer overflows, use the %.*s format specifier with a precision value that is equal to the size of the buffer. For example:
char buffer[256]; snprintf(buffer, sizeof(buffer), "%.*s", sizeof(buffer), "This is a long message that may cause a buffer overflow"); printf("%s\n", buffer);
This will print the truncated message "This is a long message that may cause a buffer overflow" on the console, without causing a buffer overflow.
4. Use the return value of printf : The return value of printf is the number of characters printed to the console, excluding the null terminator. This can be useful for error handling or for computing the size of the output. For example:
int num = 10; int n = printf("The value of num is: %d\n", num); if (n < 0) < perror("printf"); exit(EXIT_FAILURE); >printf("The size of the output is: %d\n", n);
This will print the value of num and the size of the output on the console, and it will display an error message if an error occurs.
By using macros, custom format specifiers, buffer size checking, and the return value of printf , programmers can improve the readability, reliability, and performance of their code when using printf in C++ programming.
In conclusion, printf is a powerful and versatile function in C++ that allows programmers to print formatted output to the console or a file. By using format specifiers, escape sequences, and other options, programmers can control the appearance, layout, and content of the output in a precise and efficient way.
Although printf has some drawbacks, such as its complex syntax and lack of error handling, it remains a popular and widely used function in C++ programming due to its flexibility and performance.
By following the tips and tricks discussed in this article, programmers can further improve the readability, reliability, and performance of their code when using printf in C++ programming.