Is there a version of itoa that returns how many characters were written to the buffer?

Viewed 128

I am currently calling _itoa_s and then calling strlen to figure out how many characters were written. Is there a similar method to itoa that either returns the new pointer to the start of the buffer, or returns how many characters were written? I have not been able to find a method in the standard library that provides this functionality.

EDIT:

This is for some performance sensitive code. I am using itoa because it is to my testing the fastest method of doing the string conversion using the standard library.

2 Answers

You can use the sprintf() function, which returns the number of characters written to the buffer (not including the nul terminator, BTW):

#include <stdio.h>

int main()
{
    int n;
    char str[64];
    printf("Enter number: ");
    scanf("%d", &n);
    int nc = sprintf(str, "%d", n);
    printf("Characters written = %d\n", nc);
    return 0;
}

In C++, you can simply convert an int to a string as follows:

std::string str = std::to_string(42);
auto l = str.length(); //2

To get the size easily and circumvent the need for buffers. Although you can get the char* pointer by calling str.data().

Although you might have to update your question with your code if you want more specific answers.

Related