Mixing wide and narrow output streams in the same program
In the "C Cookbook", it is mentioned that mixing cout and wcout in the same program should not be done. This comment stems from the fact that C and C standards dictate that streams have an orientation, and once this orientation is set for a stream, you should not mix operations that are incompatible with the orientation.
What does this mean in practice?
When cout or wcout is called for the first time, the orientation for stdout becomes set. In the case of cout, stdout becomes a byte-oriented stream, and in the case of wcout, stdout becomes a wide-oriented stream. Per the C standard [27.4.1] and C standard [7.19.2], once the orientation of a stream is set, you should not call a function which is not compatible with the orientation of that stream.
Exceptions to the rule
However, it is important to note that not all compilers follow this standard strictly. For example, in Visual C 10.0, the fwide function (used to set the orientation of a stream) is unimplemented. Therefore, in Visual C , mixing cout and wcout is allowed.
Similarly, in early versions of GCC, due to a bug that got fixed, it was possible to call cout and wcout in the same program by calling std::ios::sync_with_stdio(false); at the beginning of the program.
However, it is important to keep in mind that these are exceptions to the rule. In general, it is not recommended to mix wide and narrow output streams in the same program, as this can lead to unexpected behavior or undefined results.
The above is the detailed content of Why Should You Avoid Mixing cout and wcout in the Same C Program?. For more information, please follow other related articles on the PHP Chinese website!