How to add a number with leading zeros into an empty string with C++

2 Answers

0 votes
#include <iostream>
#include <string>
#include <sstream>

int main() {
    int n = 95;
 
    std::ostringstream oss;
    oss << n;
    std::string str = oss.str();
    
    size_t n_zero = 5; // Number of leading zeros
 
    auto empty_str = std::string(n_zero - std::min(n_zero, str.length()), '0') + str;
     
    std::cout << empty_str << std::endl;
}


 
 
/*
run:
 
00095
 
*/

 



answered May 25, 2024 by avibootz
edited May 25, 2024 by avibootz
0 votes
#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>

int main() {
    int n = 95;
    size_t n_zero = 5; // Number of leading zeros
    
    std::ostringstream oss;
    oss << std::setfill('0') << std::setw(n_zero) << n;
    std::string empty_str = oss.str();

    std::cout << empty_str << std::endl;
}
 
 
 
/*
run:
 
00095
 
*/

 



answered May 25, 2024 by avibootz

Related questions

1 answer 134 views
1 answer 144 views
2 answers 189 views
2 answers 145 views
2 answers 158 views
3 answers 221 views
2 answers 156 views
...