[Solved] Length problem for buffer

Started by
1 comment, last by rvdwerf 16 years, 6 months ago
Hi all :) I have some problems how i can approach this solution correctly:p First of all i created a string class with use of sprintf_s() etc Now i want to parse a numeric or decimal or float to char*, but the problem is that i want the correct sized char* buffer for that variable I dont know if it is possible or if it isnt needed here are my parse functions:

static String Parse(int number)
{
	// create result string object
	String result;
		
	// create buffer for the parsed string
	result.m_szBuffer = new char[100];

	// parse number into buffer
	sprintf_s(result.m_szBuffer, 10, "%i", number);
	result.m_iLength = (int)strlen(result.m_szBuffer);

	// return the results
	return result;
}

static String Parse(double decimal)
{
	// create result string object
	String result;
		
	// create buffer for the parsed string
	result.m_szBuffer = new char[100];

	// parse number into buffer
	sprintf_s(result.m_szBuffer, 10, "%d", decimal);
	result.m_iLength = (int)strlen(result.m_szBuffer);

	// return the results
	return result;
}

static String Parse(float real)
{
	// create result string object
	String result;
		
	// create buffer for the parsed string
	result.m_szBuffer = new char[100];

	// parse number into buffer
	sprintf_s(result.m_szBuffer, 10, "%f", real);
	result.m_iLength = (int)strlen(result.m_szBuffer);

	// return the results
	return result;
}





Now the problem is the

// create buffer for the parsed string
result.m_szBuffer = new char[100];





if i now have a very large number to parse then maybe it cannot hold the number. but if it is instead very small then i allocate useless space of memory :P If i want to save memory etc i think i have to get the length of the passed variable to create the correct buffer. but i dont know how todo it : Maybe iam doing something completly wrong forgive my noobness that time :D Thx in advance -Robbie [Edited by - rvdwerf on October 3, 2007 8:24:58 AM]
Advertisement
Well, the first problem is that you're using sprintf_s(). Seeing as it looks as you're using C++, you should probably stick to C++ idioms; one of which is to avoid the use of C style string manipulation. Such as using std::stringstream for string formatting, which will handle the buffers for you.

If you absolutely must use C string formatting functions, try using snprintf() or one if its siblings. snprintf() will give you an return value that indicates if the buffer you passed it was too small, so you can enlarge the buffer and try the operation again.
oh ok thx :)
that will help

hmm then i can better change my mind to the stringstream hehe

thx for the fast reply :D

This topic is closed to new replies.

Advertisement