Solved

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

Posted on 2014-11-09
9
180 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
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 19

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
 
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
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
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 30

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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

With most software applications trying to cater to multiple user needs nowadays, the focus is to make them as configurable as possible. For e.g., when creating Silverlight applications which will connect to WCF services, the service end point usuall…
Entering time in Microsoft Access can be difficult. An input mask often bothers users more than helping them and won't catch all typing errors. This article shows how to create a textbox for 24-hour time input with full validation politely catching …
The goal of this video is to provide viewers with basic examples to understand opening and reading files in the C programming language.
The goal of this video is to provide viewers with basic examples to understand how to create, access, and change arrays in the C programming language.

744 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now