Cout and printf

Source: Internet
Author: User
Previous understandings of the mixed results of cout and printf () originated from a judge in the Beijing Division in a certain year. According to the report, the output of a certain question in a team mixed the cout and printf () during the competition, and the output sequence was wrong. The reason is as one with buffering and one without buffering. Jin Qiang raised doubts about this, because stdio. h defines functions like ungetc (), and its function is to put the characters back into the input stream. The buffer is also used in stdio. So why is a problem with the mix of cout and printf? Next we will do some experiments (Environment: G ++ (GCC) 3.2.3 (mingw special 20030504-1 )). # Include <iostream>
Using namespace STD; int main (){
Cout <"AAA ";
Printf ("BBB ");
Return 0;
} The output is aaabbb. If you modify the program: # include <iostream>
Using namespace STD; int main (){
IOS: sync_with_stdio (false );
Cout <"AAA ";
Printf ("BBB ");
Return 0;
} An error occurred in the bbbaaa sequence. Sync_with_stdio () is defined in <ios_base>. When true is accepted as the parameter, stream operations in iostream and stdio are synchronized. The default value is true, so the result of the first program is correct. However, although the stdio sync mark is set to true by default in the C ++ standard, different compilers on different platforms may not fully support this standard. Therefore, there is a general warning about "do not mix iostream with stdio. If you modify the program: # include <iostream>
Using namespace STD; int main (){
IOS: sync_with_stdio (false );
Cout <"AAA" <flush;
Printf ("BBB ");
Return 0;
} The output of this program is correct again. Because flush forcibly clears the buffer and outputs the content.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.