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

3 Answers

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

int main() {
    std::string str = "C++";
    int totalLength = 7;
    
    if (str.length() < totalLength) {
        str.append(totalLength - str.length(), '*'); 
    }
    
    std::cout << "\"" << str << "\"" << std::endl; 
}



/*
run:

"C++****"

*/

 



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

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




/*
run:

"C++****"

*/

 



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

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

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



/*
run:

"C++****"

*/

 



answered Jul 3, 2025 by avibootz
...