need a c-string format of toString()

If you just need to convert the output of toString(), you can use

const char* s = toString().c_str();

Note that c_str simply returns a pointer to the underlying character storage of the string. So you do need to be careful to not get a pointer to the string and then having that string go out of scope, in which case the pointer may or may not still point to valid memory. Your function currently is returning a string (I'm guessing your code has using namespace std) which means a C++ string object.

If you don't absolutely need C strings, I would recommend using C++ strings, since they are more current and just easier to work with. However, if for reasons somewhere else in the code you do need a C string, your function should look like

char* toString() {
    // formatting your output
}

Because all a C string is is a null terminated ('\0') array of char, and an array is equivalent to a pointer to the first element, so that's where char* comes from.

Because of that, something needs to “own” the memory of that character array, and that something needs to have a “lifetime” that is at least as long as the scope you need it for. If you make a function that returns a raw char * you should make sure that the pointer is to either a:

  • static string literal
  • a dynamically allocated string with the new operator that you then make sure to delete later.

In either case, C++ stringstreams could make formatting your output far more intuitive. You will need #include <sstream> and then some googling will steer you in the right direction. This solution also works if you need a C string, because C++ strings have a method called c_str() that converts C++ strings into C strings (null terminated array of characters):

#include <string>
#include <sstream>
using namespace std;

string toString() {
    stringstream ss; // these are so useful!
    if (*d != 1) {
        // this probably isn't the exact formatting you are looking for,
        // but stringstreams can certainly do it if you research a bit!
        ss << *n << *d;
    }
    else {
        ss << *n;
    }
    return ss.str();
}

void function_that_needs_c_string(const char * c);

int main() {
    function_that_needs_c_string(toString().c_str());
}
Answer from Aposhian on Stack Overflow
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › standard › base-types › standard-numeric-format-strings
Standard numeric format strings - .NET | Microsoft Learn
The following example formats a numeric value as a currency string in the current culture (in this case, the en-US culture). decimal value = 123.456m; Console.WriteLine(value.ToString("C2")); // Displays $123.46
🌐
ByteHide
bytehide.com › blog › c# tostring formatting: step-by-step tutorial
C# ToString Formatting: Step-By-Step Tutorial (2026)
December 31, 2023 - Formatting decimals into currency format is as simple as saying “Hello, World!” in C#. Have a look: ... Now, that’s a price tag with professionalism written all over it! Imagine an e-commerce platform where you’re showing product prices in various currencies. ToString("C") supports localization too!
Top answer
1 of 1
1

need a c-string format of toString()

If you just need to convert the output of toString(), you can use

const char* s = toString().c_str();

Note that c_str simply returns a pointer to the underlying character storage of the string. So you do need to be careful to not get a pointer to the string and then having that string go out of scope, in which case the pointer may or may not still point to valid memory. Your function currently is returning a string (I'm guessing your code has using namespace std) which means a C++ string object.

If you don't absolutely need C strings, I would recommend using C++ strings, since they are more current and just easier to work with. However, if for reasons somewhere else in the code you do need a C string, your function should look like

char* toString() {
    // formatting your output
}

Because all a C string is is a null terminated ('\0') array of char, and an array is equivalent to a pointer to the first element, so that's where char* comes from.

Because of that, something needs to “own” the memory of that character array, and that something needs to have a “lifetime” that is at least as long as the scope you need it for. If you make a function that returns a raw char * you should make sure that the pointer is to either a:

  • static string literal
  • a dynamically allocated string with the new operator that you then make sure to delete later.

In either case, C++ stringstreams could make formatting your output far more intuitive. You will need #include <sstream> and then some googling will steer you in the right direction. This solution also works if you need a C string, because C++ strings have a method called c_str() that converts C++ strings into C strings (null terminated array of characters):

#include <string>
#include <sstream>
using namespace std;

string toString() {
    stringstream ss; // these are so useful!
    if (*d != 1) {
        // this probably isn't the exact formatting you are looking for,
        // but stringstreams can certainly do it if you research a bit!
        ss << *n << *d;
    }
    else {
        ss << *n;
    }
    return ss.str();
}

void function_that_needs_c_string(const char * c);

int main() {
    function_that_needs_c_string(toString().c_str());
}
🌐
Reddit
reddit.com › r/csharp › double.tostring() formatting
r/csharp on Reddit: Double.ToString() formatting
April 30, 2024 -

Hello all! I have a strange requirement to fulfill, and I was not able to find a proper solution for all use cases. So, the PO wants to display the measured double typed data with 5 useful digits (with possible decimal places as well). I tried the obvious F5 and G5 format strings, but they are not good for all scenarios.

For the following inputs the expected outputs are: 1.2345 -> "1.2345" 2099.1547 -> "2099.2" 1234.567 -> "1234.6" 0.000605 -> "0.0006" 0.0000001 -> "0.0"

Thanks for your help in advance!

🌐
Medium
prajapatiamit.medium.com › all-string-formatting-in-c-unlocking-the-power-of-tostring-74bee76712ba
All String Formatting in C#: Unlocking the Power of “To String()” | by Amit Prajapati | Medium
July 24, 2024 - In C#, the ToString() method is a versatile function used to convert objects to their string representation. By using format strings, developers can precisely control how values are represented, whether they are numbers, dates, or custom objects.
🌐
AI Solutions
ai-solutions.com › _help_Files › variable_tostring_1_millisecond.htm
Variable.ToString(String) Method
Converts the number held by the calling Variable into a string based on the format specifiers given by formatString. The format specifiers are standard C/C++ specifiers as used with the sprintf function. The Format method converts a double precision floating point value to a string; the IFormat ...
Find elsewhere
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › standard › base-types › formatting-types
Overview: How to format numbers, dates, enums, and other types in .NET - .NET | Microsoft Learn
A parsing operation creates an instance of a data type from its string representation. For more information, see Parsing Strings. For information about serialization and deserialization, see Serialization in .NET. The basic mechanism for formatting is the default implementation of the Object.ToString ...
🌐
Reddit
reddit.com › r/learnprogramming › [c#] understanding the tostring method
r/learnprogramming on Reddit: [C#] Understanding the ToString method
December 9, 2014 -

I know I ask a lot of questions on here. Unfortunately I am learning all this on my own with not even a single peer to talk to so I hope you all understand. I really need some help understanding the ToString method as it seems to be used frequently. I have read all over the web, essentially, the same text book response when someone asks this question. "ToString returns the the class or data specific to the class" which I understand but at the same time I dont. for instance, the following code is in my book ( condensed it a little but im sure you get the idea)...

public class Time
public override string ToString()
    {
        return string.Format("{0}:{1:D2}:{2:D2} {3}",
            ((hours == 0 || hours == 12) ? 12 : hours % 12),
            minutes, seconds, (hours > 12 ? "AM" : "PM"));
    }

I get that when you input values in the new variable that you assign for time the ToString Method can be used to display those values in a specific format.

ex. Time time = new Time();.... time.SetTime( 13,27, 24) will display as 1:27:24 PM.

What I dont get is why ToString? why "return string.Format"? couldn't we just call this method DisplayTime() and say return string(.....)?

Why is it specifically only ToString that is used here and what is the purpose of the .Format? More to the point, why use .Format instead of Console.Write?

Top answer
1 of 2
4
What you've asked is actually two entirely separate questions! ToString and Format do not have to be used together, and most often will not be. I write this with my ToString experiences being primarily in Java, but a quick scan through C# documentation shows that they aren't all that different. Let's first imagine a world without ToString(): Say you have a class, ClassA. ClassA is instantiated into ObjectA. Pretend ClassA does not inherit from anything: It is purely self-contained. Next, somewhere in your code, you use Console.Write(ObjectA); (Or any other print function really). What happens? Well, that's a very good question. An Object isn't a directly printable value. With an int, or a string, or a float, or a bool, you have one bit of data and you know how to print that. An object is a collection of data. Do you fail and throw an exception? Do you print the memory address of the object? Do you list off all public data contained in that object? How does that look? Point is, there is no easily defined behavior in printing it. You're at the mercy of whatever the compiler implemented. Fortunately, that's not how the designers implemented things. First off, there is no such thing as a standalone class: All classes inherit from Object at some point, which I assume you know. And Object contains a barebones Object.ToString(). Printing functions, Console.write() or otherwise, will call ToString() when you attempt to print an object. Console.write(ObjectA) is really calling ObjectA.ToString(). If you did not define a ToString() in ClassA, it moves up the Hierarchy until Object.ToString(), which is guaranteed to exist. Most often this is not a very useful representation. You want better. You want Console.Write(Student) to print the student ID, or name, or something intelligible at the least. And that is why you override ToString in ClassA, to be able to define your own behavior when you attempt to print an Object. -- The other question is easier, and the other commenter explained it well: It's just for a placeholder. Instead of doing all the calculations in-place and concatenating the results, you define what the formatting of the string is beforehand, and then do all the calculations together afterwards, without having to manually concatenate them all.
2 of 2
3
Let's say you have a class: public class CodingBootcamp { private int numStudents; public Foo(int NumStudents) { numStudents = NumStudents; } } And then some time later, you have an object of type CodingBootcamp, and you do: Console.WriteLine(codingBootcampObject);... then what will be written will be something like "CodingBootcamp". However, if you want it instead to say, "A Coding bootcamp with 15 students", you can override the ToString method of the CodingBootcamp class and it will do so. String.Format allows you to write a string with placeholders, like {0} and {1}. You don't want to do Console.Write because you might not always want to write to a console (in fact, you rarely do!). You could call this method DisplayTime and then call it manually, but overriding ToString allows us to edit the default string representation of this object.
🌐
DZone
dzone.com › coding › languages › c# string format examples
C# String Format Examples - DZone
December 4, 2024 - DateTime dateValue = new DateTime(2021, 4, 16, 10, 40, 0); var enUSCulture = new CultureInfo("en-US"); var itITCulture = new CultureInfo("it-IT"); Console.WriteLine("{0}: {1}", enUSCulture.Name, dateValue.ToString(enUSCulture)); // Result: en-US: 4/16/2021 10:40:00 PM Console.WriteLine("{0}: {1}", itITCulture.Name, dateValue.ToString(itITCulture)); // Result: it-IT: 16/04/2021 10.40.00 · In C# 6 or later versions, String Interpolation is recommended. String interpolation is more flexible and more readable and can achieve the same results without composite formatting.
🌐
Medium
medium.com › @anuragramteke › formatting-numbers-in-c-with-comma-separators-using-tostring-f804ae7227e0
Formatting Numbers in C# with Comma Separators using ToString | by Anurag Ramteke | Medium
July 27, 2023 - int num = 123456789; string formatted = num.ToString("#,##0"); ... You can also specify the number of decimal places you want to display by adding . and adding # and 0symbols after that.
🌐
GeeksforGeeks
geeksforgeeks.org › c# › datetime-tostring-method-in-c-set-1
DateTime.ToString() Method in C# | Set – 1 - GeeksforGeeks
July 11, 2025 - This method is used to convert the value of the current DateTime object to its equivalent string representation using the specified format and culture-specific format information.
Top answer
1 of 8
137

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");
2 of 8
36

If you have a POSIX-2008 compliant system (any modern Linux), you can use the safe and convenient asprintf() function: It will malloc() enough memory for you, you don't need to worry about the maximum string size. Use it like this:

char* string;
if(0 > asprintf(&string, "Formatting a number: %d\n", 42)) return error;
log_out(string);
free(string);

This is the minimum effort you can get to construct the string in a secure fashion. The sprintf() code you gave in the question is deeply flawed:

  • There is no allocated memory behind the pointer. You are writing the string to a random location in memory!

  • Even if you had written

    char s[42];
    

    you would be in deep trouble, because you can't know what number to put into the brackets.

  • Even if you had used the "safe" variant snprintf(), you would still run the danger that your strings gets truncated. When writing to a log file, that is a relatively minor concern, but it has the potential to cut off precisely the information that would have been useful. Also, it'll cut off the trailing endline character, gluing the next log line to the end of your unsuccessfully written line.

  • If you try to use a combination of malloc() and snprintf() to produce correct behavior in all cases, you end up with roughly twice as much code than I have given for asprintf(), and basically reprogram the functionality of asprintf().


If you are looking at providing a wrapper of log_out() that can take a printf() style parameter list itself, you can use the variant vasprintf() which takes a va_list as an argument. Here is a perfectly safe implementation of such a wrapper:

//Tell gcc that we are defining a printf-style function so that it can do type checking.
//Obviously, this should go into a header.
void log_out_wrapper(const char *format, ...) __attribute__ ((format (printf, 1, 2)));

void log_out_wrapper(const char *format, ...) {
    char* string;
    va_list args;

    va_start(args, format);
    if(0 > vasprintf(&string, format, args)) string = NULL;    //this is for logging, so failed allocation is not fatal
    va_end(args);

    if(string) {
        log_out(string);
        free(string);
    } else {
        log_out("Error while logging a message: Memory allocation failed.\n");
    }
}
🌐
Stevex
blog.stevex.net › string-formatting-in-csharp
SteveX Compiled » String Formatting in C#
The ToString method can accept a string parameter, which tells the object how to format itself - in the String.Format call, the formatting string is passed after the position, for example, "{0:##}"
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › api › system.single.tostring
Single.ToString Method (System) | Microsoft Learn
Dim numbers() As Single = {1054.32179, -195489100.8377, 1.0437E21, _ -1.0573e-05} Dim specifiers() As String = { "C", "E", "e", "F", "G", "N", "P", _ "R", "#,000.000", "0.###E-000", _ "000,000,000,000.00###"} For Each number As Single In numbers Console.WriteLine("Formatting of {0}:", number) For Each specifier As String In specifiers Console.WriteLine(" {0,5}: {1}", _ specifier, number.ToString(specifier)) Next Console.WriteLine() Next ' The example displays the following output to the console: ' Formatting of 1054.32179: ' C: $1,054.32 ' E: 1.054322E+003 ' e: 1.054322e+003 ' F: 1054.32 ' G:
🌐
Unity
discussions.unity.com › unity engine
.ToString() formatting - Unity Engine - Unity Discussions
September 6, 2019 - Is there a guide somewhere on all of the shorthand you can put in the .ToString() parenthesis? For the life of me I cannot remember how to show the sign of a number, or how to reduce a number to a certain amount of decim…
🌐
FreeASPHosting.net
freeasphosting.net › format-string-in-csharp-string-interpolation.html
Format String In C#
By using String.Format with control spacing, we ensure that the names and ages are displayed in a tabular format with consistent alignment and spacing. The ToString C# Format in C# can be used to convert a value to its string representation. It also allows custom formatting.
🌐
Unity
discussions.unity.com › unity engine
C# and ToString() - Unity Engine - Unity Discussions
August 15, 2010 - When I do the following in C# in Unity I get an error: 123456.ToString("C"); Does Unity not support the various ToString formatting options offered by C#? As show here: Custom string formatting in C# | Aaron Johnson H…
🌐
C# Corner
c-sharpcorner.com › article › understanding-tostring-vs-convert-tostring-in-c-sharp
Understanding ToString() vs Convert.ToString() in C#
May 23, 2024 - ToString(): Primarily used for converting an instance of a type to a string, typically with possible formatting options specific to the type.