user1899020
user1899020

Reputation: 13575

How to convert an integer to a string with a fixed number of digits in c++?

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);

Upvotes: 0

Views: 2395

Answers (2)

Nikanos Polykarpou
Nikanos Polykarpou

Reputation: 391

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;
}

Upvotes: 3

mohaps
mohaps

Reputation: 1020

char buf[5];
snprintf(buf, sizeof(buf), "%04d", intVal);

Upvotes: 5

Related Questions