Reputation: 67
not a question about a particular code, but in C++ the operators scanf/printf using <stdio.h>
seem the same to me as cout or cin in the header <iostream>
so can anyone just explain what the difference between the operators, why and when do we use either one? humbly apologize if this has been asked before, but
Thanks.
Upvotes: 1
Views: 1682
Reputation: 238281
scanf
and printf
are not operators. They are functions.
There is no header <iostream.h>
in the C++ standard library in any standard version of C++. You may be using an ancient dialect of C++.
when to use which?
Rough rule of thumb: Use std::cout
and std::cin
when you write C++. Don't use printf
or scanf
when writing C++.
then why was it imported to C++
As far as I understand, this is so that C programs could be converted to C++ in small incremental steps. If you have written a C program that uses C standard I/O, then you can rewrite the program in C++ without replacing the I/O part entirely. This design choice was probably to encourage existing programs / projects to move from using C to using C++.
The C I/O functions are a vestigial feature that exist for backwards compatiblity with C.
Upvotes: 1
Reputation: 267
Regular competitive programmers face common challenge when input is large and the task of reading such an input from stdin might prove to be a bottleneck. Such problem is accompanied with “Warning: large I/O data”.
cin/cout is faster than scanf/printf, key differnce among these.
Why is scanf faster than cin?
On a high level both of them are wrappers over theread() system call, just syntactic sugar. The only visible difference is that scanf() has to explicitly declare the input type, whereas cin has the redirection operation overloaded using templates. This does not seem like a good enough reason for a performance hit of 5x.
It turns out that iostream makes use of stdio‘s buffering system. So, cin wastes time synchronizing itself with the underlying C-library’s stdio buffer, so that calls to bothscanf()and cin can be interleaved.
The good thing is that libstdc++ provides an option to turn off synchronization of all the iostream standard streams with their corresponding standard C streams using
std::ios::sync_with_stdio(false);
same with cout and printf.
but in simple words, cin, cout uses extraction and insertion in c++ which are basically overloaded, hence another factor of slow speed.
I hope this answer your question of why one is preferred over another and they are basically the way to input data, and internally cin, cout is written using c stdio buffer library.
Upvotes: 1
Reputation: 802
scanf and printf come from C and taken up by C++. std::cout/cin are C++ only.
Upvotes: 1