Text Wrapping in C on Thermo Mini Printer

梦想与她 提交于 2019-11-29 18:13:44

Since you have the length of the line, it's not that hard...

Iterate over the string, one character at a time. If you see a space save the position as e.g. last_space. If your iteration goes over the max line length, then go to the last_space position and convert the space to a newline, reset the position counter to zero, and start over from that position.


Maybe implement it something like this:

#include <stdio.h>
#include <string.h>
#include <ctype.h>

#define LINE_LENGTH 32

char text[256] = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer ac risus elit, id pellentesque magna. Curabitur tempor rutrum enim, sit amet interdum turpis venenatis vel. Praesent eu urna eros. Mauris sagittis tempor felis, ac feugiat est elementum sed. Praesent et augue in nibh pharetra egestas quis et lectus. Lorem ipsum.";

static void wrap(char *text, const int length)
{
    int last_space = 0;
    int counter = 0;

    for (int current = 0; text[current] != '\0'; current++, counter++)
    {
        if (isspace(text[current]))  // TODO: Add other delimiters here
            last_space = current;

        if (counter >= length)
        {
            text[last_space] = '\n';
            counter = 0;
        }
    }
}

int main(void)
{
    printf("Before wrap:\n%s\n", text);

    wrap(text, LINE_LENGTH);

    printf("\nAfter wrap:\n%s\n", text);

    return 0;
}

Important note: The wrap function modifies the buffer passed in as the text argument. That means it can not handle literal strings as those are read-only. It works by replacing a space with a newline. If you modify the function to add more than one character, then a better solution would by to (re)allocate a new buffer big enough to hold the modified string.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!