C string creation from character format string? (very basic)

Hi Experts,

When using the standard library, I usually create string by using string directly or with ostringstream (<< operators)....

I like printf an awful lot though, and would love to be able to just do this if I wanted:

string s = myFormatFunction("%c%c%c%c%c", 'h', 'e', 'l', 'l', 'o');

after the call, of course, we get, "hello" in s.

There must already be a flavor of printf that does this or something similar in the standard library (c or C++)?  I can't seem to find it....

Thanks,
Mike
LVL 1
threadyAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

phoffricCommented:
In C++, you can just say:
string s = "hello";

In C, you can say:
char sArray[] = "hello";
or
char *sPtr = "hello";

>> There must already be a flavor of printf
Yes, sprintf "writes" to a buffer instead of a console. In their below example, "buffer" is being written to in a style similar to printf.
http://www.cplusplus.com/reference/cstdio/sprintf/?kw=sprintf
/* sprintf example */
#include <stdio.h>

int main ()
{
  char buffer [50];
  int n, a=5, b=3;
  n=sprintf (buffer, "%d plus %d is %d", a, b, a+b);
  printf ("[%s] is a string %d chars long\n",buffer,n);
  return 0;
}

Open in new window

0
n2fcCommented:
sprintf() effectively does a "print to a string"...

See: http://www.cplusplus.com/reference/cstdio/sprintf/
for a description...

Sounds like this is what you want?
0
threadyAuthor Commented:
no- I want the string as the return value.
0
Cloud Class® Course: Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

threadyAuthor Commented:
I know we can write a function to do that, but I was hoping it existed already...
0
threadyAuthor Commented:
That way, I never need to know a max buffer allocation length- it comes from my format string itself...
0
Tommy BraasCommented:
In plain C you must allocate a buffer yourself. What you can do is create a wrapper function to create your string and return it, where it calculates the overall length of the result char buffer before allocating the memory for it and printing to it.

Another option is to allocated a huge char buffer, one much larger than you would ever need, then print to it and substring it before returning.

I would suggest the first option.
0
phoffricCommented:
>> There must already be a flavor of printf that does this
Yes, but if you want to use the printf format, you do so with a char* allocated buffer or a char buffer array.
Below shows how to convert the char buffer array to a string.
You might be tempted to use sprintf on a string's c_str() function, but c_str() is used to get, not set, the underlying array. It also could be placed in read-only memory as c_str() returns a const char*.
http://www.cplusplus.com/reference/string/string/c_str/

/* sprintf example */
#include <iostream>
#include <string>
#include <stdio.h>


int main ()
{
  char buffer [50];
  int n, a=5, b=3;
  n=sprintf (buffer, "%d plus %d is %d", a, b, a+b);
  printf ("[%s] is a string %d chars long\n",buffer,n);
  
  std::string str(buffer);       // Convert the char array to a string
  std::cout << "[" << str << "] is a string " << str.size() << " chars long" << std::endl;
  
  return 0;
}

Open in new window


>> That way, I never need to know a max buffer allocation length
If that is your requirement, then you cannot use printf type formats.
0
ZoppoCommented:
Hi thready,

I'm not sure if this works for you since I guess the functions _vscprintf and vsprintf maybe are compiler specific, at least it works with VisualStudio.'s C++ compiler - if you use some other please tell.
std::string myFormatFunction( const char* pszFormat, ... )
{
	va_list args;

	va_start( args, pszFormat );

	int nLen = _vscprintf( pszFormat, args );

	char* pszBuffer = new char[ nLen + 1 ];

	vsprintf( pszBuffer, pszFormat, args );

	std::string strRet = pszBuffer;

	delete [] pszBuffer;

	return strRet;
}

Open in new window

This IMO is exactly what you asked for, it can be used like this:

    string s = myFormatFunction("%c%c%c%c%c", 'h', 'e', 'l', 'l', 'o');

Hope this helps,

ZOPPO
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
threadyAuthor Commented:
Exactly what I wanted, thank you!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C

From novice to tech pro — start learning today.