Padout text entered to a specific length adding blank spaces

Viewed 315

I am a c++ noob and I have been trying to figure out how you would pad out a line of string entered <30 char to a specific length set. I wanted to have one extra space added to each gap until the extra spaces run out max length 30 characters.

So if I have : cout << "Enter String" ;

           cin << stringentered ;

I want it to loop through adding a space until it reaches 30 char.

It__is__a__sunny day.

It___is___a___sunny___day.

It____is____a_____sunny____day. = this is the display I want at the end of the loop which = 30 characters (the _ are blank spaces).

2 Answers

There are of course many possible solutions.

I will give one example based on the following algorithm

  • Extract all words from the string
  • Calculate the sum of the charcters of all words in the string
  • The rest is available for spaces. Calculate that
  • Then we divide the the available space by the number of gaps between the words
  • There may be a rest of the integer division, This we will evenly distribute

One (of many) possible solutions could look lke the below:

#include <string>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <vector>
#include <numeric>

// Maximum filed width
constexpr size_t MaxWidth = 30u;

int main() {

    // Instruction for the user
    std::cout << "\nPlease enter a string\n";
    if (std::string stringEntered{}; std::getline(std::cin, stringEntered)) {

        // Only do something if the string is shorter than the maximum filed width (and, if the string is not empty)
        if (stringEntered.length() < MaxWidth and not stringEntered.empty()) {

            // We want to extract words (and spaces)
            std::istringstream iss(stringEntered);

            // Get all words (not white spaces) from the string
            std::vector words(std::istream_iterator<std::string>(iss), {});

            // Get accumulated length of all words
            size_t wordsLength = std::accumulate(words.begin(), words.end(), 0, [](size_t i, const std::string& s) { return i + s.length(); });

            // Get the number of separators
            size_t numberOfSeparators = (words.empty() ? 0u : words.size() - 1u);

            // How much place do we have for spaces?
            size_t spaceToDistribute = MaxWidth - wordsLength;

            // For an equal distribution, we need to know, how many spaces to print
            size_t separatorLength = spaceToDistribute / numberOfSeparators;
            int separatorLengthRest = static_cast<int>(spaceToDistribute % numberOfSeparators);

            // Now, output all words and spaces
            // Some ruler
            std::cout << std::string(MaxWidth, '.') << '\n';

            // Print result
            for (const std::string& word : words) {

                // Calculate number of spaces. Do an even distribution
                size_t numberOfSpaces = separatorLength + (((separatorLengthRest--) > 0) ? 1 : 0);

                // No spaces after last word
                if (word == words.back()) numberOfSpaces = 0;

                // Show word and spaces
                std::cout << word << std::string(numberOfSpaces,' ');
            }

            std::cout << "\n\n";
        }
    }

    return 0;
}

To be compilied with C++17.

#include <iostream>
#include <string>
#include <cctype>
#include <cstring>

using namespace std;

//Function prototypes
void padOutSpaces(string validInput);

int main()
   {
// ask for input
// initialInput = fetchInput(); 

// check that the input is not greater than 30 characters – if it is, display an error message
// initialInput = checkValidityAndAskAgain(initialInput); // haven't checked if this is valid syntax

// take input of 30 or less and fill in spaces
//padOutSpaces(initialInput);
  }

 //This will fetch the initial input from the user, any length is acceptable

 // string fetchInput() {
 //ask for input
  }

 //Check that the param is not greater than 30 characters – if it is, display an error message and asks for intput again

// string checkValidityAndAskAgain(String ) {
// while NOT string length > 30
// we ask again
    
// return value
 }

//Take input of 30 or less and fill in spaces

//void padOutSpaces(string validInput) {
// int desiredLength = 30;

// while validInput length is less than 30 aka desired length variable at the beginning of the func
// <code here>
    
    // loop through each char (up till validInput length) so we can check for spaces
    // <code here>
        
        // check if/whether at a space yet AND whether our string length is still under desired length
        // <code here>
            
            // add a space at the next index so that it now appears after the "found" space
            // <code here>
            
            // push index 1 forward forward again so it skips the next char which is the one we just inserted
            // <code here>

    //force a break out of loop. 

cout << "*********** Checked input length and it's now 30 :D" << endl;
cout << validInput << endl;

}
Related