简体   繁体   中英

Does cout/cin internally call printf() / scanf() like `new` calls malloc?

I have looked it up over the Internet. I have found many answers comparing cin vs scanf() and cout vs printf() , but never found if cin actually uses scanf() internally like new operator in C++ uses malloc() function of C.

The C++ standard does not specify how standard library facilities such as std::cin and std::cout are implemented, only how they should behave. Whether the C++ I/O functions call their C counterparts is up to the implementation.

As an example of how the C++ I/O streams can be implemented, we can look at the source code of libstdc++, which is GCC's standard library implementation. The std::basic_istream& operator>>(int&) function which is the one called when you use std::cin >> x to read an int calls some functions which call other functions and it eventually reaches this _M_extract_int function that actually parses the integer. Therefore, libstdc++ does not implement the stream extraction operator for ints using C I/O functions. Still, remember that this is only one example and other standard library implementations may be different.

C++ standard specifies what objects std::cout and std::cin must do. How it is implemented depends on vendor.

The best way to be sure is to read the source code of given implementation.

You also need to know, that under the hood printf() uses also other functions. It would be optimization wise to implement cout with them, as this object doesn't work exactly as printf() function.

There is also a little to no chance of std::cin using scanf() , as it tends to be problematic (read more onA beginners' guide away from scanf() ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM