Чем cout отличается от printf

от admin

What is the difference between printf() and cout in C++?

This is mainly used in C language. It is a formatting function that prints to the standard out. It prints to the console and takes a format specifier to print. It returns an integer value. It is not type safe in input parameters. It can be used in C++ language too.

Here is the syntax of printf() in C and C++ language,

String − Any text/message to print on console.

Format Specifier − According to the variable datatype, use format specifiers like %d, %s etc.

variable_name − Any name given to declare the variable.

Here is an example of printf() in C language,

Example

Output

Here is the output

This is used in C++ language. It is an object of iostream in C++ language. It also prints to the console. It does not take any format specifier to print. It does not return anything. It is type safe in input parameters.

Output

Here is the syntax of cout in C++ language,

string − Any text/message to print on console.

variable_name − Any name given to the variable at the time of declaration.

Printf vs cout: What is the difference?

You want to know about the difference between Printf and cout. Then you have come to the right place. If you are learning to code then this is an important topic that you should not skip. As we know C and C++ are some of the biggest programming languages out there.

C is a powerful programming language that lets you create compelling applications. C++ is derived from and has much in common with object-oriented languages such as Java. Including concepts such as classes and methods. Using a class library can be part of an application’s development rather than specific to one application.

Printf vs Cout

As the name suggests, both functions are used to display information on the screen. Printf and cout are among the most basic functions in C and C++. It is important to have a good understanding of these two functions. You can use both to print data, but whereas printf offers a higher level of flexibility, cout offers better performance.

But of them work differently in different scenarios. So you should be well versed in them. In this article, we’ll compare these two functions and learn how they differ from one another. But before it let’s look at them separately.

What is printf?

Printf is a function in the C programming language used to format the output. It is a powerful tool for programmers to display output in different ways. You can use printf to print data from one column to another column, from row to column, and from row to row. The printf function is one of the most essential functions in any programming language.

To be more specific it takes a format string and several arguments. And prints the arguments using the format specifiers in the format string. You can use Printf for standard output, files, or other programs. This function is available in many languages, including C, C++, Java, etc.

It provides a powerful alternative to using the standard cout statement. It’s essential to keep in mind that printf does not automatically advance the cursor’s position as cout does, but it does provide many additional benefits that make it well worth your time to use it.

You can see the syntax below on how to use them.

Syntax for Printf

What is cout?

In C++, cout is also a function used to display output on the computer screen. In other words, it is a standard I/O stream that serves as the default standard input and output device for C++ programs. The cout object is created by the IOstream library and automatically opened when a program starts running. You can use cout to print out text strings and numbers. You can also use it to display the value of a character variable or a string variable.

It is usually used in conjunction with other commands or functions. The output of cout can be either stored in a string or displayed on the screen. It depends on the formatting. By default, cout will display output to the screen. However, if you want to store it for future use, you can use the setf() function to change its behavior. You can also specify the number of digits that are displayed after the decimal point using setprecision()

Syntax for Cout

When to use printf and cout?

It is really up to you and the type of code. Both of these functions are very versatile and powerful. But when you are a newbie it is good to stick to simplicity. As you get more advanced you work with complex functions. As the differences go there are many differences between printf and cout, the most striking difference is the formatting.

Although both of these functions have benefits, it’s important to note that if you want to output special characters or change how data is displayed, printf is your best option.

Remember that although cout may seem easier to use at first glance because it doesn’t require any parameters, it’s much less versatile than printf.

If you’re working on a C++ project that requires immediate output to be presented in a GUI format, then printf is your best option. However, if you want to save data for later use or debug your code without leaving the editor, using cout will be more beneficial.

Conclusion

I hope you like this article about printf vs cout As we’ve learned in this article, both printf and cout have pros and cons. While I prefer printf for its simplicity and readability, you may feel differently. Which do you prefer using? Let us know in the comments below!

'printf' vs. 'cout' in C++

What is the difference between printf() and cout in C++?

16 Answers 16

I’m surprised that everyone in this question claims that std::cout is way better than printf , even if the question just asked for differences. Now, there is a difference — std::cout is C++, and printf is C (however, you can use it in C++, just like almost anything else from C). Now, I’ll be honest here; both printf and std::cout have their advantages.

Real differences

Extensibility

std::cout is extensible. I know that people will say that printf is extensible too, but such extension is not mentioned in the C standard (so you would have to use non-standard features — but not even common non-standard feature exists), and such extensions are one letter (so it’s easy to conflict with an already-existing format).

Unlike printf , std::cout depends completely on operator overloading, so there is no issue with custom formats — all you do is define a subroutine taking std::ostream as the first argument and your type as second. As such, there are no namespace problems — as long you have a class (which isn’t limited to one character), you can have working std::ostream overloading for it.

However, I doubt that many people would want to extend ostream (to be honest, I rarely saw such extensions, even if they are easy to make). However, it’s here if you need it.

Syntax

As it could be easily noticed, both printf and std::cout use different syntax. printf uses standard function syntax using pattern string and variable-length argument lists. Actually, printf is a reason why C has them — printf formats are too complex to be usable without them. However, std::cout uses a different API — the operator << API that returns itself.

Generally, that means the C version will be shorter, but in most cases it won’t matter. The difference is noticeable when you print many arguments. If you have to write something like Error 2: File not found. , assuming error number, and its description is placeholder, the code would look like this. Both examples work identically (well, sort of, std::endl actually flushes the buffer).

While this doesn’t appear too crazy (it’s just two times longer), things get more crazy when you actually format arguments, instead of just printing them. For example, printing of something like 0x0424 is just crazy. This is caused by std::cout mixing state and actual values. I never saw a language where something like std::setfill would be a type (other than C++, of course). printf clearly separates arguments and actual type. I really would prefer to maintain the printf version of it (even if it looks kind of cryptic) compared to iostream version of it (as it contains too much noise).

Translation

This is where the real advantage of printf lies. The printf format string is well. a string. That makes it really easy to translate, compared to operator << abuse of iostream . Assuming that the gettext() function translates, and you want to show Error 2: File not found. , the code to get translation of the previously shown format string would look like this:

Now, let’s assume that we translate to Fictionish, where the error number is after the description. The translated string would look like %2$s oru %1$d.\n . Now, how to do it in C++? Well, I have no idea. I guess you can make fake iostream which constructs printf that you can pass to gettext , or something, for purposes of translation. Of course, $ is not C standard, but it’s so common that it’s safe to use in my opinion.

Читать:
Какую версию юнити лучше скачать

Not having to remember/look-up specific integer type syntax

C has lots of integer types, and so does C++. std::cout handles all types for you, while printf requires specific syntax depending on an integer type (there are non-integer types, but the only non-integer type you will use in practice with printf is const char * (C string, can be obtained using to_c method of std::string )). For instance, to print size_t , you need to use %zu , while int64_t will require using %"PRId64" . The tables are available at http://en.cppreference.com/w/cpp/io/c/fprintf and http://en.cppreference.com/w/cpp/types/integer.

You can’t print the NUL byte, \0

Because printf uses C strings as opposed to C++ strings, it cannot print NUL byte without specific tricks. In certain cases it’s possible to use %c with ‘\0’ as an argument, although that’s clearly a hack.

Differences nobody cares about

Performance

Update: It turns out that iostream is so slow that it’s usually slower than your hard drive (if you redirect your program to file). Disabling synchronization with stdio may help, if you need to output lots of data. If the performance is a real concern (as opposed to writing several lines to STDOUT), just use printf .

Everyone thinks that they care about performance, but nobody bothers to measure it. My answer is that I/O is bottleneck anyway, no matter if you use printf or iostream . I think that printf could be faster from a quick look into assembly (compiled with clang using the -O3 compiler option). Assuming my error example, printf example does way fewer calls than the cout example. This is int main with printf :

You can easily notice that two strings, and 2 (number) are pushed as printf arguments. That’s about it; there is nothing else. For comparison, this is iostream compiled to assembly. No, there is no inlining; every single operator << call means another call with another set of arguments.

However, to be honest, this means nothing, as I/O is the bottleneck anyway. I just wanted to show that iostream is not faster because it’s "type safe". Most C implementations implement printf formats using computed goto, so the printf is as fast as it can be, even without compiler being aware of printf (not that they aren’t — some compilers can optimize printf in certain cases — constant string ending with \n is usually optimized to puts ).

Inheritance

I don’t know why you would want to inherit ostream , but I don’t care. It’s possible with FILE too.

Type safety

True, variable length argument lists have no safety, but that doesn’t matter, as popular C compilers can detect problems with printf format string if you enable warnings. In fact, Clang can do that without enabling warnings.

«printf» против «cout» в C ++

В чем разница между printf() и cout в С++?

16 ответов

Я удивлен, что все в этом вопросе утверждают, что std::cout намного лучше, чем printf , даже если вопрос просто попросил разницы. Теперь есть разница — std::cout — это С++, а printf — C (однако вы можете использовать его на С++, как и все, что угодно от C). Теперь, я буду честен здесь; как printf , так и std::cout имеют свои преимущества.

Отказ от ответственности: я более опытен с C, чем С++, поэтому, если есть проблема с моим ответом, не стесняйтесь редактировать или комментировать.

Реальные различия

расширяемость

std::cout является расширяемым. Я знаю, что люди скажут, что printf также расширяется, но такое расширение не упоминается в стандарте C (поэтому вам придется использовать нестандартные функции, но не существует общей нестандартной функции), и такие расширения являются одной буквой (поэтому легко конфликтует с уже существующим форматом).

В отличие от printf , std::cout полностью зависит от перегрузки оператора, поэтому нет проблем с пользовательскими форматами — все, что вы делаете, это определение подпрограммы, принимающей std::ostream как первый аргумент, а ваш тип — второй. Таким образом, нет проблем с пространством имен, поскольку у вас есть класс (который не ограничивается одним символом), вы можете иметь для него перегрузку std::ostream .

Однако я сомневаюсь, что многие люди захотят расширить ostream (честно говоря, я редко видел такие расширения, даже если их легко сделать). Однако, здесь, если вам это нужно.

Синтаксис

Как легко заметить, оба printf и std::cout используют разные синтаксисы. printf использует стандартный синтаксис функций, используя строки шаблонов и списки аргументов переменной длины. На самом деле, printf — причина, по которой C имеет их — форматы printf слишком сложны, чтобы их можно было использовать без них. Однако std::cout использует другой API — API operator << , который возвращает себя.

Как правило, это означает, что версия C будет короче, но в большинстве случаев это не имеет значения. Разница заметна, когда вы печатаете много аргументов. Если вам нужно написать что-то вроде Error 2: File not found. , считая номер ошибки, и его описание будет заполнителем, код будет выглядеть так. Оба примера работают тождественно (ну, вроде, std::endl на самом деле сбрасывает буфер).

Хотя это не кажется слишком сумасшедшим (это всего в два раза больше), все становится более сумасшедшим, когда вы на самом деле форматируете аргументы, а не просто печатаете их. Например, печать чего-то типа 0x0424 просто сумасшедшая. Это вызвано состоянием смешивания std::cout и фактическими значениями. Я никогда не видел языка, где нечто вроде std::setfill было бы типом (отличным от С++, конечно). printf четко разделяет аргументы и фактический тип. Я бы предпочел сохранить версию printf (даже если она выглядит как загадочная) по сравнению с ее версией iostream (поскольку она содержит слишком много шума).

Перевод

Здесь находится реальное преимущество printf . Строка формата printf хорошо. строка. Это делает его очень легко переводить по сравнению с operator << злоупотреблением iostream . Предполагая, что функция gettext() преобразуется, и вы хотите показать Error 2: File not found. , код, который должен получить перевод ранее показанной строки формата, будет выглядеть так:

Теперь предположим, что мы переводим на Fictionish, где номер ошибки после описания. Переведенная строка будет выглядеть как %2$s oru %1$d.\n . Теперь, как это сделать на С++? Ну, я понятия не имею. Думаю, вы можете сделать фальшивый iostream , который строит printf , который вы можете передать в gettext или что-то еще для перевода. Конечно, $ не является стандартом C, но он настолько распространен, что он безопасен для использования по моему мнению.

Не нужно запоминать/искать специальный синтаксис целочисленного типа

C имеет множество целочисленных типов, а также С++. std::cout обрабатывает все типы для вас, а printf требует определенного синтаксиса в зависимости от целочисленного типа (существуют нецелые типы, но единственным нецеловым типом, который вы будете использовать на практике с printf , является const char * ( C, можно получить с помощью метода to_c std::string )). Например, для печати size_t вам нужно использовать %zd , а для int64_t потребуется использовать %»PRIu64″d . Таблицы доступны в http://en.cppreference.com/w/cpp/io/c/fprintf и http://en.cppreference.com/w/cpp/types/integer.

Вы не можете напечатать байт NUL, \0

Поскольку printf использует строки C, а не строки С++, он не может печатать NUL-байт без конкретных трюков. В некоторых случаях в качестве аргумента можно использовать %c с ‘\0’ , хотя это явно хак.

Различия, которые никто не заботится о

Производительность

Обновление. Оказывается, что iostream настолько медленный, что он обычно медленнее вашего жесткого диска (если вы перенаправляете свою программу в файл). Отключение синхронизации с stdio может помочь, если вам нужно вывести большое количество данных. Если производительность является реальной проблемой (в отличие от написания нескольких строк в STDOUT), просто используйте printf .

Все думают, что они заботятся о производительности, но никто не мешает ее измерять. Мой ответ заключается в том, что ввод-вывод является узким местом в любом случае, независимо от того, используете ли вы printf или iostream . Я думаю, что printf может быть быстрее, чем быстрый просмотр сборки (скомпилированный с помощью clang с использованием опции -O3 компилятора). Предполагая, что пример моей ошибки, printf пример делает меньше вызовов, чем пример cout . Это int main с printf :

Вы можете легко заметить, что две строки и 2 (число) выставляются как аргументы printf . Это об этом; нет ничего другого. Для сравнения это iostream скомпилировано для сборки. Нет, нет вставки; каждый вызов operator << означает другой вызов с другим набором аргументов.

Однако, честно говоря, это ничего не значит, так как I/O является узким местом в любом случае. Я просто хотел показать, что iostream не быстрее, потому что он «type safe». Большинство реализаций C реализуют форматы printf с использованием вычисленного goto, поэтому printf работает так быстро, даже если компилятор не знает о printf (а не о том, что это не так), некоторые компиляторы могут оптимизировать printf в в некоторых случаях — постоянная строка, заканчивающаяся на \n , обычно оптимизируется до puts ).

Наследование

Я не знаю, почему вы хотели бы наследовать ostream , но мне все равно. Возможно также с помощью FILE .

Тип безопасности

Правда, списки аргументов переменной длины не имеют безопасности, но это не имеет значения, поскольку популярные компиляторы C могут обнаруживать проблемы с строкой формата printf , если вы включаете предупреждения. Фактически, Clang может сделать это без включения предупреждений.

Похожие статьи