Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Andrzejek on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Convert CString to unsigned short in MFC?

Status
Not open for further replies.

Rmck87

Programmer
Jul 14, 2003
182
US
Hello, I am attempting to convert a CString variable (strTemp, which is coming from an edit control) into a WORD (m_cmd, aka unsigned short). I have been trying to figure this out for over a week now and have come to nothing.

I am familiar with sscanf and was using:

sscanf_s(strTemp, "%x", &m_cmd);

However, %x is used for DWORDS, and every time I would use this, it would overwrite whatever m_cmd was next to in the stack.

Thanks in advance!

One Ring to Rule Them All, One Ring to Find Them, One Ring to Bring Them All, and in the Darkness Bind Them.
 
Why not convert to a DWORD and then copy that DWORD value into the short?
 
Would I not lose any data in the conversion from DWORD to WORD?

One Ring to Rule Them All, One Ring to Find Them, One Ring to Bring Them All, and in the Darkness Bind Them.
 
You'd lose no more data then you'd lose converting directly to the WORD itself.

By the way, I assume there is a way to convert directly to the word, but I don't know it off the top of my head with sscanf_s.
 
That's true. Do you know know of another method that doesn't use sscanf_s?

One Ring to Rule Them All, One Ring to Find Them, One Ring to Bring Them All, and in the Darkness Bind Them.
 
Maybe a std::stringstream would be better?
Code:
WORD num;
std::stringstream ss;
ss << strTemp;
ss >> num;
 
Note that if it is a CString, you need to use the LPCTSTR operator to get a const char* out of it otherwise it may link but it will almost definitely crash.
 
Try atoi(const char*) from <stdlib.h>. CString to const char* conversion is possible then returned int value will be truncated to unsigned short. Alas, atoi does not perform any error checks...

 
atoi doesn't do hex. You probably need to use strtol for hex and octal.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top