简体   繁体   中英

How can I use _stprintf in my programs, with and without UNICODE support?

Microsoft's <tchar.h> defines _stprintf as swprintf if _UNICODE is defined, and sprintf if not. But these functions take different arguments! In swprintf , the second argument is the buffer size, but sprintf doesn't have this.

Did somebody goof? If so, this is a big one. How can I use _stprintf in my programs, and have them work with and without _UNICODE ?

You're seeing parallel evolution here. swprintf is a latecomer to standard C, after it was discovered that (A) 8 bits is insufficient for text and (B) you should pass buffer sizes along with buffers. TCHAR is a microsoft idea to unify ASCII and Unicode APIs. They dropped the ball, missing point (B). The proper TCHAR solution should have been to define _stprintf as either swprintf or snprintf .

The solution is then to simply wrap <tchar.h> and do this yourself.

these functions take different arguments!

There are two different versions available with MS compilers. Take a look here . This is in keeping with the ANSI standard. But I think that does not answer your question. I'll skip it for a while and rather tell you how you can have uniformity.

have them work with and without _UNICODE?

You are better off using the 'safe string functions' as per MS recommendations. See this . Use `_stprintf_s' and I think you will get around your problem.

Did somebody goof?

EDITED: I don't think so. I don't have the Rationale handy to give you the answer. I'll post an update when I get my hands on something more concrete. In the meantime look at MSalters' explanation.

A curious thing is MS's C runtime does not claim compatibility with the ISO standard.

Disclaimer: I am not defending the giant of Redmond, only pointing out stuff that strikes me as odd!

This may not be directly answering the question, but one alternative is to use _stprintf_s . You have to add the extra parm, but then it will still compile both ways, and is more future-proof.

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