Solved

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

Posted on 2014-11-09
9
183 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 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
Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

 
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: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Microsoft App Store does not Download and Update the apps in Windows 10 5 85
Visual Studio 2015 locks debug executable 9 181
Problem to file 3 74
Post a good COM tutorial 1 54
For most people, the WrapPanel seems like a magic when they switch from WinForms to WPF. Most of us will think that the code that is used to write a control like that would be difficult. However, most of the work is done by the WPF engine, and the W…
A theme is a collection of property settings that allow you to define the look of pages and controls, and then apply the look consistently across pages in an application. Themes can be made up of a set of elements: skins, style sheets, images, and o…
The goal of this video is to provide viewers with basic examples to understand opening and writing to files in the C programming language.
The goal of this video is to provide viewers with basic examples to understand opening and reading files in the C programming language.

786 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