Solved

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

Posted on 2014-11-09
9
189 Views
Last Modified: 2014-11-10
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
0
Comment
Question by:thready
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
9 Comments
 
LVL 32

Expert Comment

by:phoffric
ID: 40431610
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
 
LVL 20

Expert Comment

by:n2fc
ID: 40431614
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
 
LVL 1

Author Comment

by:thready
ID: 40431625
no- I want the string as the return value.
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 1

Author Comment

by:thready
ID: 40431632
I know we can write a function to do that, but I was hoping it existed already...
0
 
LVL 1

Author Comment

by:thready
ID: 40431635
That way, I never need to know a max buffer allocation length- it comes from my format string itself...
0
 
LVL 14

Expert Comment

by:Tommy Braas
ID: 40431653
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
 
LVL 32

Expert Comment

by:phoffric
ID: 40431715
>> 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
 
LVL 31

Accepted Solution

by:
Zoppo earned 500 total points
ID: 40432147
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
 
LVL 1

Author Closing Comment

by:thready
ID: 40432427
Exactly what I wanted, thank you!
0

Featured Post

[Live Webinar] The Cloud Skills Gap

As Cloud technologies come of age, business leaders grapple with the impact it has on their team's skills and the gap associated with the use of a cloud platform.

Join experts from 451 Research and Concerto Cloud Services on July 27th where we will examine fact and fiction.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This tutorial is posted by Aaron Wojnowski, administrator at SDKExpert.net.  To view more iPhone tutorials, visit www.sdkexpert.net. This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho…
What my article will show is if you ever had to do processing to a listbox without being able to just select all the items in it. My software Visual Studio 2008 crystal report v11 My issue was I wanted to add crystal report to a form and show…
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use for-loops in the C programming language.
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use nested-loops in the C programming language.

623 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question