'Why is my function not outputting what I am returning?

I am trying to write a piece of code that justifies an input by inserting extra spaces between words, so that its length is exactly 40 characters.

I have written a function that I think should do this;

string justify(int size, string s) {
    while (size < 40) {
        for (int p = 0; p < size; p++) {
            if (s[p] == ' ') {
                s.insert(p, " ");
            }
        }
    }
    return s;
}

However, when I call the function later;

justify(words.size(), words);

Nothing happens. I am defining the string in int main() and am then calling the function. Why is it not working?



Solution 1:[1]

There is a huge amount of bugs in your code: size is not bound to s.size() (and you actually need s.size()). The inner loop will be infinite too, because p was growing with the same speed as s.size(). This is the fixed algorithm - I marked three main changes with inline comments.

But it is not correct for strings without any spaces at all.

#include <iostream>

using namespace std;

string justify (string s)
{
  int l = s.size();
  while (s.size () < 40)
  {
    for (int p = 0; p < s.size() && s.size () < 40; p++) {
      // s.size () < 40 - not to add odd spaces

      if (s[p] == ' ')
      {
        s = s.insert(p, " ");

        while(p < s.size() && s[p] == ' ')
          p++; // Now p grows faster than s.size()

      }
    }
    if (l == s.size()) { // If no spaces in s!
        break;
    }
    l = s.size();
  }
  return s;
}

int main ()
{
  cout << justify("HelloWorld");

  return 0;
}

Solution 2:[2]

The subject, as far as the code you wrote, I really don't understand it. Are you sure that when the size is greater than 40, your program will not fall into an infinite loop?

Another point: I hope you notice that what you pass to the function is a copy of the string. If you want to modify your string in justify, then you need to pass a reference (&), or, after justify returns, follow assign values in main, such as "str = justify(...);"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Peter Mortensen
Solution 2 Peter Mortensen