Issue with sprintf function

Hello forum!

I am getting a strange error through Visual Studio when I use sprintf in my program.

So, in my code, I define a struct with a few internal variables.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
struct ROB_DTA 
{
	int Blue1_ID;
	int Blue2_ID;
	int Red1_ID;
	int Red2_ID;

	string Blue1_DTA;
	string Blue2_DTA;
	string Red1_DTA;
	string Red2_DTA;

	bool Blue1_Occ;
	bool Blue2_Occ;
	bool Red1_Occ;
	bool Red2_Occ;
};

ROB_DTA Robot_Users; 


Later on in my program, I assign a value to Blue1_DTA, Blue2_DTA, so on and so forth. I then try to use sprintf to compress some of these values together..
1
2
char queueddata[256];
sprintf(queueddata, "%s %s %s", Robot_Users.Blue2_DTA, Robot_Users.Red1_DTA, Robot_Users.Blue1_DTA);


But upon execution Visual Studio halts the program and explains that there was an internal error with my sprintf code. When I look at the value for queueddata, it is filled with gibberish.

What is the problem? Does sprintf not work with this kind of pointer? I honestly don't know.

Any help will be appreciated!
-Kaleb
¿Which pointers? You are passing string objects, resulting in a bad cast.
I would recommend to use stringstream
If you really want to work with sprintf then you need to use the c_str() method to obtain a const char * from the strings
You may have seen sample code on Windows that uses %s to format strings. But those strings will be ATL CStrings. This error happened so frequently with MFC CStrings that the ATL ones were formatted to do the right thing when used like this.
@ne555, Sorry, I incorrectly typed in pointers in my original post!
I went the path of using c_str() and it works perfectly now. Thanks!

@kbw Thanks for the info! I did not realize that upon using sprintf. Definitely worth noting.

-Kaleb
Topic archived. No new replies allowed.