How to add N zeros to an empty string in C++

2 Answers

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

std::string addToEmptyStr(std::string pad, int len) {
    std::string str = ""; 
    
    while (str.length() < len) {
        str += pad;
    }
    
    return str;
}

int main(int argc, char* argv[]) {
    int n = 4;

    std::string empty_string = addToEmptyStr("0", n);
    
    std::cout << empty_string << std::endl;
}



/*
run:

0000

*/

 



answered May 27, 2024 by avibootz
0 votes
#include <iostream>
#include <string>

int main(int argc, char* argv[]) {
    int n = 4;
 
    std::string empty_string = std::string(n, '0');

    std::cout << empty_string << std::endl;
}



/*
run:

0000

*/

 



answered May 27, 2024 by avibootz

Related questions

2 answers 173 views
1 answer 134 views
134 views asked May 26, 2024 by avibootz
1 answer 133 views
1 answer 142 views
2 answers 164 views
1 answer 156 views
2 answers 142 views
142 views asked May 26, 2024 by avibootz
...