-2

The goal of this program should be to produce a output string such that:

  1. The output string + spaces in between == the width.
  2. The strings are not cut off. So, it gives out complete words per line.

This is what I have so far:

int main()
{
    int width= 15;
    vector<string> line;
    line.push_back("Hello");
    line.push_back("My");
    line.push_back("Name");
    line.push_back("Is");
    line.push_back("John");

    auto s = line.front();
    for (auto i = std::size_t {1}; i < line.size(); ++i) s += ' ' + line[i];


    for (size_t i = 0; i < s.length(); i+=width+1)
    {
        s.insert(i,"\n");
    }

    cout<<s;

}

I wan't to add spaces in between the words evenly so the last string won't get cutoff and it moves to the next line.

This is similar to the question of C++ text full justification but I want to correct my own implementation to the solution of this problem .

Community
  • 1
  • 1
Sadij
  • 51
  • 8

1 Answers1

3

What you're doing is you're inserting the new line inside the string after it has already been formed, thus possibly cutting a word down to the new line.

It would be better to check if the string's length would become bigger than your line's desired width if you insert a new word before adding another word to it.

This is what I could come up with

int main()
{
    int width= 15;
    vector<string> line;
    line.push_back("Hello");
    line.push_back("My");
    line.push_back("Name");
    line.push_back("Is");
    line.push_back("John");

    std::string s {};
    for (int i {0}; i < line.size(); ++i)
        {
            if( (s + line[i] + " ").size() <= width)
            {
                s += line[i] + " ";
            }
            else
            {
                s += "\n" + line[i] + " ";
                width += width;
            }
        }
    cout<<s;
}
Reousa Asteron
  • 519
  • 1
  • 3
  • 18