I am trying to write a code that ensures that the number of characters per line are at the most 80 without separating words (it will be stored in a txt file). I'm not really sure what type of c functions will help me do that.
CodePudding user response:
Your question is way too broad and there are many ways to answer it, but here is an intuitive and easy-to-read one, it's neither optimized for performance nor for memory-safe operations but rather for the sake of understanding how to write an algorithm.
std::vector<std::string> lines;
std::string text = "The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.";
const size_t lineLimit = 80;
size_t lastOffset = 0;
while (lastOffset < text.size() - lineLimit)
{
// find the next blank space index,
// -1 is because the offset starts at zero
size_t nextSpace = text.find(" ", lastOffset lineLimit - 1);
// if there aren't any blank spaces left, break the loop
if (nextSpace == -1) break;
// add a line of text from text[lastOffset] to text[nextSpace]
lines.push_back(std::string(text.data() lastOffset, nextSpace - lastOffset));
// we need to add 1 to skip the blank
// space right after the text[nextSpace]
lastOffset = nextSpace 1;
}
// add anything left in the buffer as the last line
lines.push_back(std::string(text.data() lastOffset));
for (std::string& line : lines)
{
std::cout << line << '\n';
}
CodePudding user response:
You could just read each line into a std::string
and then search for whitespace characters in the first 80 characters, starting from the 80:th character. If a whitespace is found, take the substring of that part - else, you'll have to break at 80 even though it's within a word.
Example:
#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>
int main() {
constexpr size_t max_len = 80;
std::string line;
while (std::getline(std::cin, line)) {
while (line.size() > max_len) { // longer than max_len, try to find a space
auto it =
std::find_if(line.rend() - max_len, line.rend(),
[](unsigned char ch) { return std::isspace(ch); });
if (it != line.rend()) { // space found in the first max_len characters
auto len = std::distance(it, line.rend());
std::cout << line.substr(0, len - 1) << "\n";
line = line.substr(len);
} else { // no space found - break at max_len
std::cout << line.substr(0, max_len) << '\n';
line = line.substr(max_len);
}
}
std::cout << line << '\n';
}
}