#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm> // Added for std::count
// Function to split a string into words
std::vector<std::string> splitString(const std::string &input) {
std::vector<std::string> words;
std::istringstream iss(input);
std::string word;
while (iss >> word) {
words.push_back(word);
}
return words;
}
// Function to justify text
std::string justifyText(const std::string &text, int lineLength) {
std::vector<std::string> words = splitString(text);
std::string result = "";
std::string currentLine = "";
for (const std::string &word : words) {
if (currentLine.empty()) {
currentLine = word;
} else {
if (currentLine.length() + word.length() + 1 <= lineLength) {
currentLine += " " + word;
} else {
// Distribute spaces evenly in the line
int spacesToAdd = lineLength - currentLine.length();
if (spacesToAdd > 0) {
int spaceCount = std::count(currentLine.begin(), currentLine.end(), ' '); // Corrected
int spacesPerGap = spacesToAdd / spaceCount;
int extraSpaces = spacesToAdd % spaceCount;
size_t pos = currentLine.find(' ');
while (pos != std::string::npos) {
currentLine.insert(pos, spacesPerGap, ' ');
if (extraSpaces > 0) {
currentLine.insert(pos, 1, ' ');
extraSpaces--;
}
pos = currentLine.find(' ', pos + spacesPerGap + 1);
}
}
result += currentLine + "\n";
currentLine = word;
}
}
}
if (!currentLine.empty()) {
result += currentLine;
}
return result;
}
int main() {
std::string text = "Ok so I have to write a program which reads a text and then formats it by adding spaces between the words. The output text must have exactly 60 characters in each line. The most spaces between words shouldn't differ by more than one space from the least spaces between words (of the same line). More spaces should be furthest to the right. If needed, the program can also move some words from one line to the next, in order to not exceed the 60 character limit.";
int lineLength = 60;
std::string justifiedText = justifyText(text, lineLength);
std::cout << justifiedText << std::endl;
return 0;
}