C++ Equivalent of Sprintf

C++ equivalent of sprintf?

std::ostringstream

Example:

#include <iostream>
#include <sstream> // for ostringstream
#include <string>

int main()
{
std::string name = "nemo";
int age = 1000;
std::ostringstream out;
out << "name: " << name << ", age: " << age;
std::cout << out.str() << '\n';
return 0;
}

Output:

name: nemo, age: 1000

Creating C formatted strings (not printing them)

Use sprintf. (This is NOT safe, but OP asked for an ANSI C answer. See the comments for a safe version.)

int sprintf ( char * str, const char * format, ... );

Write formatted data to string Composes a string with the same text
that would be printed if format was used on printf, but instead of
being printed, the content is stored as a C string in the buffer
pointed by str.

The size of the buffer should be large enough to contain the entire
resulting string (see snprintf for a safer version).

A terminating null character is automatically appended after the
content.

After the format parameter, the function expects at least as many
additional arguments as needed for format.

Parameters:

str

Pointer to a buffer where the resulting C-string is stored. The buffer
should be large enough to contain the resulting string.

format

C string that contains a format string that follows the same
specifications as format in printf (see printf for details).

... (additional arguments)

Depending on the format string, the function may expect a sequence of
additional arguments, each containing a value to be used to replace a
format specifier in the format string (or a pointer to a storage
location, for n). There should be at least as many of these arguments
as the number of values specified in the format specifiers. Additional
arguments are ignored by the function.

Example:

// Allocates storage
char *hello_world = (char*)malloc(13 * sizeof(char));
// Prints "Hello world!" on hello_world
sprintf(hello_world, "%s %s!", "Hello", "world");

c++ equivalent of this code below (sprintf)

I would suggest an ostringstream:

string name;
{
ostringstream oss;
oss << "jari" << (rank+42+size) << ".jpg";
name = oss.str();
}

Details: To use this solution, you'll want #include <sstream> and pull ostringstream into scope with using std::ostringstream; (or just use std::ostringstream directly qualified).

Equivalent of sprintf in C#?

It turned out, that what I really wanted was this:

short number = 17;
System.IO.BinaryWriter writer = new System.IO.BinaryWriter(stream);
writer.Write(number);
writer.Flush();

The key here is the Write-function of the BinaryWriter class. It has 18 overloads, converting different formats to a byte array which it writes to the stream. In my case I have to make sure the number I want to write is kept in a short datatype, this will make the Write function write 2 bytes.

Is there a C# equivalent for C sprintf(result, %5.5s , stringValue)

There is nothing dirctly equivalent, not with #.

You can come close using Substring and Math.Min:

String.Format("{0,5}", stringValue.Substring(0, Math.Min(stringValue.Length, 5)));

std::string formatting like sprintf

You can't do it directly, because you don't have write access to the underlying buffer (until C++11; see Dietrich Epp's comment). You'll have to do it first in a c-string, then copy it into a std::string:

  char buff[100];
snprintf(buff, sizeof(buff), "%s", "Hello");
std::string buffAsStdStr = buff;

But I'm not sure why you wouldn't just use a string stream? I'm assuming you have specific reasons to not just do this:

  std::ostringstream stringStream;
stringStream << "Hello";
std::string copyOfStr = stringStream.str();

C equivalent of Python format method

There isn't an equivalent function unless you make one yourself because, unlike python, strings in C are simple arrays and it's you who is responsible for allocating as much memory as you need, passing a pointer to a function, and freeing it later. That's why in functions like sprintf you need to specify an output array (and optionally a size value in variants like snprintf).

A custom implementation would be something like this (not including error checks to keep things simple):

#include <string.h>
#include <stdlib.h>
#include <stdarg.h>

#define STRSIZE 256

char* my_sprintf(const char* fmt, ...) {
/* Create a temporary buffer */
char temp[STRSIZE];
/* Get variadic arguments */
va_list args;
va_start(args, fmt);
/* Use the variadic argument variant of snprintf
* The return value is the number of characters that would have been written,
* if the buffer was sufficiently large. We use this to determine if we
* need to repeat on a larger buffer to account for strings of any length */
int len = vsnprintf(result, STRSIZE, fmt, args);
/* Cleanup */
va_end(args);
/* If the entire string fits in the temp buffer, return a copy */
if (len < STRSIZE)
return strdup(temp);
/* Otherwise, allocate enough memory and repeat */
char* result = (char*)malloc(len + 1); // +1 for the null terminator
/* The variadic argument pack is consumed already, so recreate it */
va_start(args, fmt);
/* Use the variadic argument variant of sprintf
* (we already have enough allocated memory now, so no need for snprintf) */
vsprintf(result, fmt, args);
/* Cleanup */
va_end(args);
return result;
}

When you're done, don't forget to free the returned pointer!

char* my_string = my_sprintf("My %s", "format");
...
free(my_string);

Using sprintf with std::string in C++

Your construct -- writing into the buffer received from c_str() -- is undefined behaviour, even if you checked the string's capacity beforehand. (The return value is a pointer to const char, and the function itself marked const, for a reason.)

Don't mix C and C++, especially not for writing into internal object representation. (That is breaking very basic OOP.) Use C++, for type safety and not running into conversion specifier / parameter mismatches, if for nothing else.

std::ostringstream s;
s << "Type=" << INDEX_RECORD_TYPE_SERIALIZATION_HEADER
<< " Version=" << FORMAT_VERSION
// ...and so on...
;
std::string output = s.str();

Alternative:

std::string output = "Type=" + std::to_string( INDEX_RECORD_TYPE_SERIALIZATION_HEADER )
+ " Version=" + std::to_string( FORMAT_VERSION )
// ...and so on...
;

C#: php sprintf equivalent

You are looking for String.Format:

String myStr = String.Format("There are {0} hits, {1} are an exact match",
number1, number2);

The format specifiers are a bit different than in PHP. Here is an article explaining format specifiers.



Related Topics



Leave a reply



Submit