stdio vs iostream
When I search on the internet for the difference between these two libraries, everyone says that <iostream>
is the standard I/O library of C++ and <cstdio>
is for C. My professor says that cin>>
and cout<<
are not good functions and if we use cin>>
many times our application will definitely crash. He also says that stdio
provides nearly 3 times faster input and output than iostream
. However, I prefer using iostream
because it is more convenient, and also I don't know if my professor is right.
So what do you advise me to use?
Using iostream
should not make your program crash. It can be slow, but that's only because it's trying to interoperate with stdio
. That synchronization can be turned off1. iostream
is the idiomatic C++ way to get input, and I'd recommend its use over stdio
functions in most cases when using C++.
1 using std::ios::sync_with_stdio(false);
Use streams in C++ and stdio.h in C. Yes, streams are a bit slower, but do those milliseconds count? User input is rarely a bottleneck of an application.
And if streams are used properly, and your compiler/runtime libraries are ok, your application won't crash.
But, if you have good, explainable reasons to use cstdio
functions, then it is fully legitimate to use them in C++ as well.
Unless performance of the I/O REALLY matters, use whichever makes your program the clearest (easiest to read).
In the vast number of programs I've written, only a few have needed special treatment to "how fast the I/O is" - and most of the problem with std::stream
functions has to to with the actual parsing of the input [as well as sync with stdio] - which, if you are reading, say, floating point numbers, will be quite difficult to write your own version of [that accepts the full range of formats that std::stream
allows].
If I/O performance REALLY matters, then using std::stream::read
and std::stream::write
may be the solution, but in most cases, best performance comes from using the non-portable mmap
and MapViewOfFile
interfaces that "map" the contents of a file directly from the filesystem to the virtual memory of the application. This saves on the amount of copying the processing of the data takes, and will make it a little faster.
上一篇: 这是C ++中最快的输入方法
下一篇: stdio vs iostream