C string to C++ string

I'm just learning about the windows API, and I encountered a line of code that looks like C but is described in the Win32 SDK Reference Help as so

The wsprintf function formats and stores a series of characters and values in a buffer. Any arguments are converted and copied to the output buffer according to the corresponding format specification in the format string. The function appends a terminating null character to the characters it writes, but the return value does not include the terminating null character in its character count.


1
2
3
4
5
6
int wsprintf(

    LPTSTR lpOut,	// pointer to buffer for output 
    LPCTSTR lpFmt, 	// pointer to format-control string 
    ...	// optional arguments
   );


Here is the source code of the basic window program that uses this function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/* Lesson 2 - Understanding Messages and Events
 * Pravin Paratey ()
**/

#include <windows.h>

HWND hwndMain;	//Main window handle

// Callback function
LRESULT CALLBACK MainWndProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam);

// Windows entry point
int WINAPI
WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, INT nCmdShow)
{
	MSG msg; // MSG structure to store messages
	WNDCLASSEX wcx; // WINDOW class information

	// Initialize the struct to zero
	ZeroMemory(&wcx,sizeof(WNDCLASSEX));
	wcx.cbSize = sizeof(WNDCLASSEX); // Window size. Must always be sizeof(WNDCLASSEX)
	wcx.style = CS_HREDRAW|CS_VREDRAW |CS_DBLCLKS ; // Class styles
	wcx.lpfnWndProc = (WNDPROC)MainWndProc; // Pointer to the callback procedure
	wcx.cbClsExtra = 0; // Extra byte to allocate following the wndclassex structure
	wcx.cbWndExtra = 0; // Extra byte to allocate following an instance of the structure
	wcx.hInstance = hInstance; // Instance of the application
	wcx.hIcon = NULL; // Class Icon
	wcx.hCursor = LoadCursor(NULL, IDC_ARROW); // Class Cursor
	wcx.hbrBackground = (HBRUSH)(COLOR_WINDOW); // Background brush
	wcx.lpszMenuName = NULL; // Menu resource
	wcx.lpszClassName = "Lesson2"; // Name of this class
	wcx.hIconSm = NULL; // Small icon for this class

	// Register this window class with MS-Windows
	if (!RegisterClassEx(&wcx))
		return 0;

	// Create the window
	hwndMain = CreateWindowEx(0, //Extended window style
				"Lesson2", // Window class name
				"Lesson 2 - A simple win32 application", // Window title
				WS_OVERLAPPEDWINDOW, // Window style
				CW_USEDEFAULT,CW_USEDEFAULT, // (x,y) pos of the window
				CW_USEDEFAULT,CW_USEDEFAULT, // Width and height of the window
				HWND_DESKTOP, // HWND of the parent window (can be null also)
				NULL, // Handle to menu
				hInstance, // Handle to application instance
				NULL); // Pointer to window creation data

	// Check if window creation was successful
	if (!hwndMain)
		return 0;

	// Make the window visible
	ShowWindow(hwndMain,SW_SHOW);

	// Process messages coming to this window
	while (GetMessage(&msg,NULL,0,0))
	{
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}
	// return value to the system
	return msg.wParam;
}

// Callback procedure
LRESULT CALLBACK MainWndProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam)
{
    POINT pt;
    char str[100];
	switch (msg)
	{
		case WM_DESTROY:
			// User closed the window
			PostQuitMessage(0);
			break;
		case WM_LBUTTONDOWN:
            pt.x = LOWORD(lParam);
            pt.y = HIWORD(lParam);
            wsprintf(str,"Co-ordinates are\nX=%i and Y=%i",pt.x,pt.y);
            MessageBox(hwnd, str, "Left Button Clicked", MB_OK);
            break;
		default:
			// Call the default window handler
			return DefWindowProc(hwnd,msg,wParam,lParam);
	}
	return 0;
}


The line of code of interest is on line 81.
wsprintf(str,"Co-ordinates are\nX=%i and Y=%i",pt.x,pt.y);

All this line does is sends a string to MessageBox including integer values. I would like to know how to rewrite this line to send a string with int values and all to the MessageBox function with more standard C++ techniques using the string, iostream, and standard libraries.

Last edited on
Hello, I made a small example that shows some C and C++ style string operations. I strongly recommend that u use the C++ way of doing it, unless it's realy needed to use an older method.

Also I would advise not to use the % placeholders, due to format string errors that might occur when invalid data is entered by the user.

Only use C style strings in combination with propper checking of the size of the string and the destination buffer, to prevent stack overflows.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// string_formatting.cpp : main project file.
#include "stdafx.h"  // Specific header for visual c++
#include <iostream>
#include <stdio.h>
#include <string>

using namespace std;

struct points
{
	int x;
	int y;
};

int main(int argc, char* argv[])
{
    points pt;
	pt.x = 12;
	pt.y = 15;
	char str[100];  // declaration of an array with room for 100 values of type char.
	char *value;    // declaration of a pointer that can point to a memory object containing data of type char
	
	/**************************************************************************************************************
	// wsprintf(str,"Co-ordinates are\nX=%i and Y=%i",pt.x,pt.y);

	First I'll show the C-Style string functions.
	however, when you use these funtions, you must make sure the strings that you want to copy or concatenate
	do fit in the buffer, otherwise your program has the risk of stack overflows,
	which result in segmentation fault or acces violation error.

	**************************************************************************************************************/

	// first copy the first part as a constant string into destination str.
	// functions that take char* as input you can also give a char[] as input without the [];
	// in fact char str[100]; is the same as char* str; followed by str = new char[100];
	strcpy(str,"Co-ordinates are\nX=");

	// here we dynamically allocate a piece of memory and assign its start adress to value,
	// so now value has something to point to.
	value = new char;
	// itoa converts the integer value in pt.x to char* value, using base/radix 10
	itoa(pt.x,value,10);
	// strcat appends char* value to destination char* str
	strcat(str,value);
	// now append the second constant part to str.
	strcat(str," and Y=");
	// now the y value into char *value;
	itoa(pt.y,value,10);
	// the last concatenation and our string is complete.
	strcat(str,value);
	// time to show the results on the screen.
	cout<<"C-Style string:\n"<<str<<endl<<endl;

	/**************************************************************************************************************
    
	here, the second part, I am going to show how to do the same thing with member functions of class string.
	this new way of operating on strings is better in means of stability.
	
	**************************************************************************************************************/

	// mind that the uppercase String is the dataobject and the lowercase string is the type
	string String;

	// put the first constant part in the string. assign() replaces all conent that's allready in the string.
	String.assign("Co-ordinates are\nX="); 
	itoa(pt.x,value,10); // I haven't found a c++ way of doing this yet.

	// here I use append() for adding a string or char* to the end of the string.
	String.append(value);

	// operator+= works almost the same as append in the previous line.
	String+=" and Y=";
	itoa(pt.y,value,10);
	String+=value;
	
	// and again, show the results.
	cout<<"The newer c++ way:\n"<<String<<endl<<endl;
	
	return 0;
}


for more information on c-style string functions, I refer to:
http://www.cplusplus.com/reference/clibrary/cstring/

and for more on c++ string member functions check:
http://www.cplusplus.com/reference/string/string/

I hope this helps, Regards, Ronnie van Aarle.
Topic archived. No new replies allowed.