0

For examples, with 4 digits, convert 0 to "0000"; and 12 to "0012".

Any good way in c++?

Sorry not making it clear, my compiler doesn't support snprintf, and I want a function like

std::string ToString(int value, int digitsCount);

3
  • <sstream> provides that sort of formatting capability, as does ye olde sprintf. Commented Dec 17, 2012 at 21:00
  • @chris you mean snprintf(), right? Commented Dec 17, 2012 at 21:00
  • @H2CO3, Indeed. I don't use it, so I guess I could lie and argue I was talking about the base of that set of functions. Commented Dec 17, 2012 at 21:04

2 Answers 2

5
char buf[5];
snprintf(buf, sizeof(buf), "%04d", intVal);
Sign up to request clarification or add additional context in comments.

7 Comments

No, please, don't sprintf()! If you use this function family, use the secure version!
@Caribou That's not a problem, the printf() family of functions works just fine in C++, but really, the secure variations should be used.
@H2CO3, I'm using sprintf on a static char buffer allocated on the stack with a length specified by me. so given all of this, sprintf() is secure enough. I posted the snprintf() version if that's more preferable :)
@H2CO3 I suppose it is probably a reasonable lightweight way of outputting what the OP wants - streams just come to me more readily these days....
@Caribou the problem with sprintf is that one day you WILL eventually change your buffer from static to mallocated one, you also will change its size, etc. So it IS insecure. Because we're humans and we make mistakes. Why not prevent them? Adding an 'n' should not hurt.
|
3

Maybe something like this

#include <iostream>
#include <iomanip>
#include <sstream>

using namespace std;

string ToString(int value,int digitsCount)
{
    ostringstream os;
    os<<setfill('0')<<setw(digitsCount)<<value;
    return os.str();
}

int main()
{
    cout<<ToString(0,4)<<endl;
    cout<<ToString(12,4)<<endl;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.