Skip to main content
gamedev.net
🔒 Locked

Untitled

Started by nivlekio 3 replies 700+ views
Original Post
nivlekio
nivlekio
Hey guys why does this not work? all i get is NULL....

#include <windows.h>
#include <iostream>
#include <stdio.h>

using namespace std;


void main()
{
	char szChar[256];
	string sAlias = "Nivlekio";

	sprintf_s(szChar,sizeof(szChar), "Alias: %s", sAlias);

	while(1)
	{
		cout << szChar;
	};
}

ChaosEngine
ChaosEngine
because std::string is not a char array.if you must do this, use c_str() as follows
sprintf_s(szChar,sizeof(szChar), "Alias: %s", sAlias.c_str());


However, the correct C++ way is to use a stringstream.

#include <string>#include <iostream>#include <sstream>using namespace std;int main() // NEVER use void main(){    stringstream stream;    string alias = "Nivlekio";    stream << "Alias: " << alias;    cout << stream.str();}


Shorter, safer and standard compliant.
if you think programming is like sex, you probably haven't done much of either.-------------- - capn_midnight
Rydinare
Rydinare
Quote:
Original post by nivlekio
Hey guys why does this not work? all i get is NULL....

*** Source Snippet Removed ***


First, don't do this. If you're using C++ constructs, use full C++ constructs. You're better off using std::ostringstream instead of sprintf and always use std::strings over raw strings.

That being said, the reason why this didn't work is that you used the format specifier of %s, yet you provided a C++ string class instead of a raw string. You'd need to do sAlias.c_str() in your sprintf_s call, instead of just sAlias. That's one major downside of using unsafe calls like sprintf is that you leave the world of type safety.
nivlekio
nivlekio
Ok kool thanks guys :)
Zahlman
Zahlman
I assume this is only a toy example, since there is no reason to copy a string into a buffer and then output the buffer; just output the string.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.