none
Convert: int to char array -- Convert string to char array

    Question

  • As discussed in another thread the MessageBox and MessageBoxA examples below work if the 'input' is a a char array...

    But what if...

    int myInt = 27; // the 'input' is an int like this instead of a char array?

    string myStr = "Hello"; // or if the 'input' is a string like this instead of a char array?

    I'm guessing you have to 'convert' myInt  or myStr to a char array as it seems MessageBox wants a char array for 'input'

    I've found a bunch of stuff on converting and re-casting things... but I guess I've missed the two cases above.

    Thanks for any help on this.

    PS: I was successful in 'converting' the sample array used in the other post from "Howdy" to "Hello" (as requested) but it took a lot to keep that conversion from coming out "Yo Dog!" :-)   (only kidding, of course)

    char myArray[100]="Hello";
    
    /* demo 1 */
    int size = MultiByteToWideChar(CP_ACP, 0, myArray, -1, NULL, 0);
    WCHAR* message = new WCHAR[size];
    size = MultiByteToWideChar(CP_ACP, 0, myArray, -1, message, size);
    MessageBox(0, message, L"Demo1", MB_OK);
    delete[] message;
    
    /* demo 2 */
    MessageBoxA(0,myArray,"Demo2",MB_OK);



    • Edited by Mel_3 Thursday, June 07, 2012 7:17 PM
    Thursday, June 07, 2012 7:15 PM

Answers

  • You should get into the habit of using wide character strings, such as:

    wchar_t Hello[6]; // instead of

    char Hello[6];

    Thus the following will work:

    MessageBox (0, L"Hello", MB_OK);
    std::wstring mystring = L"Hello again";
    MessageBox (0, mystring.c_str (), MB_OK);
     

    Thursday, June 07, 2012 8:09 PM
  • >does anybody why do I get the Warning noted in the comments?

    >while(!num<total) // warning

    This evaluates as:

    while((!num)<total) // warning

    The result of the expression !num is true or false - a bool.
    You then compare it (a bool) for *less than* total.

    By contrast, this:

    while(!(num<total)) // no warning

    evaluates as "while num<total is not true".

    - Wayne

    Thursday, June 07, 2012 10:41 PM
  • What I'm trying to strongly suggest to you (a point which you seem to be missing), is that there should be no reason to use char strings in your code at all. Nowadays, you should be using wchar_t arrays for all your string constants. Then there is no reason to "migrate a string to a char array". Strings are character arrays to begin with. Just make sure they are wide character strings.
    Friday, June 08, 2012 3:48 PM
  • the code is intended to take an array of standard 8-bit byte characters... ASCII characters... and migrate/convert them to wide (2-byte wide) characters...
     
    Are you saying it does not do that?
     
    Are you saying the 2-byte characters results are not unicode compliant?
    ASCII characters use only 7 bits (0-127), and all encodings agree on those. The code points 128-255 have different meanings for different code pages. For most purposes the Windows 1252 code page is the same as Latin 1, and for Latin 1 the code points 0-255 are the same as in 16-bit Unicode (UTF-16).
     

    David Wilkinson | Visual C++ MVP
    Saturday, June 09, 2012 5:30 PM

All replies

  • You should get into the habit of using wide character strings, such as:

    wchar_t Hello[6]; // instead of

    char Hello[6];

    Thus the following will work:

    MessageBox (0, L"Hello", MB_OK);
    std::wstring mystring = L"Hello again";
    MessageBox (0, mystring.c_str (), MB_OK);
     

    Thursday, June 07, 2012 8:09 PM
  • >But what if...
    >int myInt = 27; // the 'input' is an int like this instead of a char array?

    This example will convert an int and will work
    whether a Unicode build is done, or Multi-Byte
    (or "Not Set" - SBCS) is used,

    #include "stdafx.h"
    #include <windows.h>

    int _tmain(int argc, _TCHAR* argv[])
    {
      int myInt = 27;
      _TCHAR msg[100];
      _stprintf(msg, _T("myInt = %d"), myInt);
      MessageBox(NULL, msg, _T("Conversion Test"), MB_OK);

      return 0;
    }

    - Wayne

    • Edited by WayneAKing Thursday, June 07, 2012 8:39 PM
    Thursday, June 07, 2012 8:38 PM
  • Well, leave it to me to do it the hard way... by 'long hand'

    I gin'd up the following code from scratch right after my original post...and it works !
    It will convert an int to a char array and display it using MessageBoxA...

    (does anybody why do I get the Warning noted in the comments? How can I fix it?)

    And thanks for your responses Brian and Wayne!

    Here is my 'long hand' solution... which I'm sure can be cleaned up... but the concept works just fine. Maybe someone else may have a use for it for whatever.

    #include<stdio.h>
    #include<iostream>
    #include<string>
    #include<Windows.h>
    using namespace std;
    
    int main()
    {
    	int num = 3125;				//we will convert this int to a char array so MessageBoxA can display it
    	int digits = 0;
    	int total = num;
    	while(!num<total)			//Warning - unsafe use of 'bool' in operation - Why ??
    	{
    		total = total/10;
    		digits = digits+1;
    	}					//digits now equals the number of digits in the number we are processing
    
    	int t_dig = 0;
    	int t_num;
    	int n = 0;				//indicates which char poisition in myArray
    	char myArrayX[100];			//will hold number as ascii characters - max 100 digit number
    	while (digits!=0)
    	{
    		t_dig=digits;
    		t_num=1;
    		while(t_dig!=1)			//calc t_num such that zeros equal to digits in num
    		{
    			t_num = t_num*10;
    			t_dig = t_dig-1;
    		}				//now t_num has zeros equal to digits in num
    
    		myArrayX[n]=48+(num/t_num);	//place the current digit, as ascii character, into the array
    		while(num>t_num)		//now reduce num to the remainder
    		{
    			num=num-t_num;
    		}
    		n=n+1;
    		digits=digits-1;		//down to this many digits left to process
    	}
    	myArrayX[n]=0;				//all done - now jus add the terminating zero
    
    	MessageBoxA(0,myArrayX,"int converted to char array",MB_OK); 	// now display the results !!!!
    	return 0;
    }



    • Edited by Mel_3 Thursday, June 07, 2012 10:17 PM
    Thursday, June 07, 2012 10:15 PM
  • >does anybody why do I get the Warning noted in the comments?

    >while(!num<total) // warning

    This evaluates as:

    while((!num)<total) // warning

    The result of the expression !num is true or false - a bool.
    You then compare it (a bool) for *less than* total.

    By contrast, this:

    while(!(num<total)) // no warning

    evaluates as "while num<total is not true".

    - Wayne

    Thursday, June 07, 2012 10:41 PM
  • >How can I fix it?

    I haven't examined your algorithm for suitability or
    errors, but if you want to maintain the same result
    as your original code but without the warning:

    while(int(!num)<total)

    Note that a bool - the result of !num - will be
    true or false, and when cast to an int will become
    either 0 or 1.

    With a value of 3125 in num, the expression num
    will evaluate as true, and hence become 1 after a
    cast to int. The expression !num will evaluate
    as false, and hence become 0 after a cast to int.
    Ergo, the expression while(int(!num)<total) is
    equivalent to while(0<total) for any value of num
    other than zero.

    - Wayne
    Thursday, June 07, 2012 11:17 PM
  • >Well, leave it to me to do it the hard way... by 'long hand'

    By the way, have you tested your algorithm with
    negative values in num?

    - Wayne
    Thursday, June 07, 2012 11:24 PM
  • Thanks for the comments Wayne.

    Here is an improved version that works for positive int's, negative int's, 0, and -0;

    I chose to display negative int's with a preceding minus sign...

    I'm sure this code can possibly be improved and simplified...
    - and I'm sure there are probably simpler ways to do this with some kind of cast or existing class or method or whatever...
    - but it felt good to code this from scratch... and make the actual steps/process somewhat clear.

    Here is the improved version for anyone that may find it or the concept useful and/or educational...

    #include<stdio.h>
    #include<iostream>
    #include<string>
    #include<Windows.h>
    using namespace std;
    
    int main()
    {
    	int num = 3125;				//we will convert this int to a char array so MessageBoxA can display it
    	//int num = 0;				//converting zero works
    	//int num = -3125;			//converting negative number works
    	//int num = -0;				//converting negative zero works
    
    	int digits = 0;
    	int total = num;
    	int t_dig = 0;
    	int t_num;
    	int n = 0;				//indicates which char poisition in myArray
    	char myArrayX[100];			//will hold number as ascii characters - max 100 digit number
    	
    	if (num<0)				//num = negetive number case
    		{num=abs(num);
    		total=num;
    		myArrayX[n]='-';
    		n=n+1;}
    
    	while(total>0)
    	{
    		total = total/10;
    		digits = digits+1;
    	}					//digits now equals the number of digits in the number we are processing
    
    	while (digits!=0)
    	{
    		t_dig=digits;
    		t_num=1;
    		while(t_dig!=1)			//calc t_num such that its magnitude = num's magnitude
    		{				//i.e. num = 3125 t_num=1000, num=372 t_num=100, etc
    			t_num = t_num*10;
    			t_dig = t_dig-1;
    		}				//now t_num & num are of the same magnitude
    
    		myArrayX[n]=48+(num/t_num);	//place the current digit, as ascii character, into the array
    		while(num>t_num)		//now reduce num to the remainder
    		{
    			num=num-t_num;
    		}
    		n=n+1;
    		digits=digits-1;		//down to this many digits left to process
    	}
    	if (num==0)				//num = 0 case
    		{myArrayX[0]=48;
    		n=n+1;}
    
    	myArrayX[n]=0;				//all done - now just add the terminating zero
    
    	MessageBoxA(0,myArrayX,"int converted to char array",MB_OK);
    	return 0;
    }
    

    Friday, June 08, 2012 12:53 PM
  • Much easier to migrate a string to a char array...

    Here's that code for anybody that is interested...

    /* stringToCharArray */
    
    #include<stdio.h>
    #include<iostream>
    #include<string>
    #include<Windows.h>
    using namespace std;
    int main()
    {
    	string myStr="Hello World";		//migrate this string
    	char myArray[100];				//to this char array
    	int n;
    	for (n=0; n < myStr.length();n++)
    	{
    		myArray[n] = myStr[n];		//stuff this character into this (n) array position
    	}
    	myArray[n]=0;					//now add a terminating zero.
    	MessageBoxA(0,myArray,"String Converted to char Array",MB_OK); // it works!
      return 0;
    }
    

    Friday, June 08, 2012 1:21 PM
  • Brian, here is my implementation of your suggestion... using MessageBox as opposed to MessageBoxA...

    I first had to migrate the provided 'byte' char array to a wide char array... since I was working with a previously populated 'byte' array...

    And as a side note my earlier example showing how to convert an int to a char array
    ...could be easily modified to move the numbers into a wide array...
    ... but my quick glance tells me it probably wouldn't save any code...
    ... but you could then use MessageBox as opposed to MessageBoxA.

    Regardless... here is the code I came up with for migrating a given byte char array to a wide char array and displaying it using MessageBox as opposed to MessageBoxA

    Thanks for the help everyone.

    	char bArray[100]="Hello World";				//migrate characters from this 'byte' Array
    	wchar_t wArray[100];					//to this wide Array... and display using MessageBox
    	int n =0;						//array index
    	while(bArray[n]!=0)
    	{
    		wArray[n]=bArray[n];				//move the character
    		n=n+1;
    	}
    	wArray[n]=0;						//add terminating zero
    	MessageBox(0,wArray,L"byte Array To wide Array",MB_OK); //it works!
    
    

    Friday, June 08, 2012 2:24 PM
  • What I'm trying to strongly suggest to you (a point which you seem to be missing), is that there should be no reason to use char strings in your code at all. Nowadays, you should be using wchar_t arrays for all your string constants. Then there is no reason to "migrate a string to a char array". Strings are character arrays to begin with. Just make sure they are wide character strings.
    Friday, June 08, 2012 3:48 PM
  • Brian, I understand your point and it is a good one.

    This started out with code where the char array was populated by ADO reading and writing text fields from an external database.

    As time permits I will see if the char array that 'receives' the contents of the selected text field of the selected record can in fact be a wide character array... probably can... do you know?

    But when it comes time to write text to the selected text field of the selected record... right now that text resides in a char array that is the historical 1-byte per character... as opposed a 2-bytes per character 'wide' char array...  so I'm not sure what will happen if that char array is converted to a wide char array...  I'll check on that as well when I can cram it in...

    Thanks for the help.

    Saturday, June 09, 2012 1:31 PM
  • Wayne,

    It seems stdafx.h is not included in VC++ Express... right?

    thanks.

    Saturday, June 09, 2012 2:32 PM
  • stdafx.h is a file that is generated by the project wizard and is part of each individual project, not a Microsoft file.

    You normally edit it as desired to make the project's #include operations more efficient.

    Saturday, June 09, 2012 3:19 PM
  •     char bArray[100]="Hello World"; //migrate characters from this 'byte' Array
        wchar_t wArray[100]; //to this wide Array... and display using MessageBox
        int n =0; //array index
        while(bArray[n]!=0)
        {
            wArray[n]=bArray[n]; //move the character
            n=n+1;
        }
        wArray[n]=0; //add terminating zero
    MessageBox(0,wArray,L"byte Array To wide Array",MB_OK); //it works!
    This code only works for ASCII (or Latin 1) strings.
     

    David Wilkinson | Visual C++ MVP
    Saturday, June 09, 2012 4:07 PM
  • the code is intended to take an array of standard 8-bit byte characters... ASCII characters... and migrate/convert them to wide (2-byte wide) characters...

    Are you saying it does not do that?

    Are you saying the 2-byte characters results are not unicode compliant?

    Thanks.

    Saturday, June 09, 2012 4:37 PM
  • well when i put this into my VC++ Express code...

    #include "stdafx.h"

    (as in Wayne's sample early on in this thread)

    I get an error when I try to compile it...

    Should VC++ Express compile such?

    Thanks.

    Saturday, June 09, 2012 4:40 PM
  • the code is intended to take an array of standard 8-bit byte characters... ASCII characters... and migrate/convert them to wide (2-byte wide) characters...
     
    Are you saying it does not do that?
     
    Are you saying the 2-byte characters results are not unicode compliant?
    ASCII characters use only 7 bits (0-127), and all encodings agree on those. The code points 128-255 have different meanings for different code pages. For most purposes the Windows 1252 code page is the same as Latin 1, and for Latin 1 the code points 0-255 are the same as in 16-bit Unicode (UTF-16).
     

    David Wilkinson | Visual C++ MVP
    Saturday, June 09, 2012 5:30 PM
  • well when i put this into my VC++ Express code...
     
    #include "stdafx.h"
     
    (as in Wayne's sample early on in this thread)
     
    I get an error when I try to compile it...
     
    Should VC++ Express compile such?
    When you set up your project, if you did not specify to use precompiled headers (it seems that you did not) then your project does not have an stdafx.h file and you should not try to #include it.
     

    David Wilkinson | Visual C++ MVP
    Saturday, June 09, 2012 5:37 PM