Click here to Skip to main content
15,921,793 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
As a novice of VC++,

I want to confirm that maximum of integer variable can convert to char sizeof 6.

For example,
C++
int x;

CString s = L"";

char    CHAR6BYTES[6];

s.Format(_T("%06d"), x);

::ZeroMemory(CHAR6BYTES,6);

WideCharToMultiByte(CP_ACP, s.GetBuffer(), s.GetLength(), CHAR6BYTES, 6, NULL, NULL);

Is this best ways to convert integer variable to char 6 size variable?
Or who knows the better ways...

Thank you in advance.

What I have tried:

Finding 2 hours web searching ...
Posted
Updated 10-Sep-17 20:48pm
v3

That is one way of doing it. But why are you creating a Unicode string and then converting to ASCII. Create in ASCII in the first instance, something like:
C++
char sNumber[7];
sprintf_s(sNumber, 7, "%06d", x);
 
Share this answer
 
Comments
CPallini 11-Sep-17 2:35am    
Indeed. My 5.
Your code rises many questions.
  1. Why do you want to limit the output to six characters (while, you know, int can be much more bigger)?
  2. Why are you trying to represent a uninitialized value (x)?
  3. Why are you first representing the int value with a wide string and then converting it to ANSI one?


Richard code, addressing very carefully point 3, shows the way to go. However, if you remove the six characters constraint, you could also use the following approach:
C++
#include<iostream>
#include <sstream>
using namespace std;

int main()
{
  int i = 12345;

  string s;
  ostringstream iss;
  iss << i;
  s = iss.str();
  cout << "the string representation of the number is " << s << endl;
}
 
Share this answer
 
Comments
Richard MacCutchan 11-Sep-17 2:55am    
For C++ much better than my suggestion. +5
CPallini 11-Sep-17 4:19am    
Your code is really fine.
By the way, thank you.
I don't program in C++, not unless I have to. So when I get stuck, Google Search is my first go to as I know that I am not the only one who has encountered the problems that I experience. A quick search proves that every time.

So, the internet can be a powerful help tool, your best friend, and your mentor, when used. This search link has tonnes of solutions for you: c++ convert int to char[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900