Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,955 questions

51,897 answers

573 users

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 110 views
1 answer 123 views
2 answers 156 views
2 answers 120 views
2 answers 127 views
3 answers 170 views
2 answers 136 views
...