Unicode CString conversion to int
Hello, if I try to convert a CString object to int in Multibyte character set mode, I face no problem.
Code:
CString strNumber = _T("1234");
int nNumber = atoi(strNumber.GetBuffer(strNumber.GetLength()));
cout << nNumber <<endl;
But if I go for unicode character set, I get the following error.
Quote:
error C2664: 'atoi' : cannot convert parameter 1 from 'unsigned short *' to 'const char *'
How can I succeed with the conversion? Thanks.
Re: Unicode CString conversion to int
Every string API has TCHAR version which compiles both for Multibyte and Unicode. You can find this in MSDN topic for the function. For atoi, this is _tstoi:
int nNumber = _tstoi(strNumber.GetBuffer(strNumber.GetLength()));
Re: Unicode CString conversion to int
Thanks. Let me look into it.
Re: Unicode CString conversion to int
Hi! Im newbie in VisualC++ and this if my fisrt message...
What's that "_t" we have to add? Is it only in VS 2008 ??
I've been googling around but it doesn't manage "_t" properly. :(
Re: Unicode CString conversion to int
That is a macro that get expanded to different things depending on whether UNICODE is defined.
Take the example of atoi in this example.
atoi is for the non-unicode version and _wtoi is for the unicode version.
As Alex F mentioned, if you use _tstoi it would get expanded to either atoi or _wtoi depending on whether the build you are taking is a unicode build or not.
The _T("string") macro is used for strings which gets expanded to L"string" for unicode and simply "string" for non-unicode builds.
Re: Unicode CString conversion to int
Thanks superman.
When I read a .txt file (made by NOtepad) with CFile class and then print on screen what I find on file, there are usually bad characters at the end. It doesn't matter if I read 5, 10 or 20 bytes.
Code:
CFile f;
f.Open(m_file, CFile::modeRead);
CHAR s[80];
int bytesread=f.Read(s,10);
f.Close();
m_out+=s; //m_out is "Cstring" linked to an EDIT CONTROL box)
UpdateData(FALSE);
(Im making an MFC app).
Should I declare "s" as unicode ? How is it ?
Or should I avoid CFile commands?
Re: Unicode CString conversion to int
Declare as
WCHAR s[80];
If you want it to work for both unicode and non-unicode without a code change, declare as
TCHAR s[80];
Re: Unicode CString conversion to int
You're seeing "bad" characters because your character array is not NULL terminated. Just add the following to your code and you should be fine:
Code:
CFile f;
f.Open(m_file, CFile::modeRead);
CHAR s[80];
int bytesread=f.Read(s,10);
f.Close();
s[10] = 0; // NULL terminator - (the 10 is just the number of bytes you read).
m_out+=s; //m_out is "Cstring" linked to an EDIT CONTROL box)
UpdateData(FALSE);
Hope that helps.