How to pad a string on the left in C++

3 Answers

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

std::string padLeft(const std::string& str, size_t totalLength, char padChar = ' ') {
    if (str.length() >= totalLength) return str;
    
    return std::string(totalLength - str.length(), padChar) + str;
}

int main() {
    std::string padded = padLeft("C++", 7, '*');
    
    std::cout << padded << std::endl; 
}



/*
run:

****C++

*/

 



answered Jul 4, 2025 by avibootz
0 votes
#include <iostream>
#include <iomanip>
#include <sstream>

int main() {
    std::ostringstream oss;
    std::string str = "C++";
    
    oss << std::right << std::setfill('*') << std::setw(6) << str;
    
    std::cout << oss.str() << std::endl;
}



/*
run:

***C++

*/

 



answered Jul 4, 2025 by avibootz
0 votes
#include <iostream>

int main() {
    std::string str = "c++";
    
    if (str.length() < 7) {
        str.insert(0, 7 - str.length(), '*');
    }
    
    std::cout << str << std::endl; 
}



/*
run:

****c++

*/

 



answered Jul 4, 2025 by avibootz
...