Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting a string into multiple lines of a specific length in C/C++

Is there a common C/C++ library (or common technique) for taking a line(s) of input text and splitting the words into separate lines. Where each line of output has a max width and words are not split across lines. Whitespace being collapsed or preserved is ok. Punctuation must be preserved. Small and compact library is preferred.

I could easily spend an afternoon putting something together that works, but would like to know if there is something common out there so I don't re-invent the wheel. Bonus points if the input line can contain a format specifier to indicate an indention level for the output lines.

Example input: "Shankle drumstick corned beef, chuck turkey chicken pork chop venison beef strip steak cow sausage. Tail short loin shoulder ball tip, jowl drumstick rump. Tail tongue ball tip meatloaf, bresaola short loin tri-tip fatback pork loin sirloin shank flank biltong. Venison short loin andouille.

Example output (target width = 60)

123456789012345678901234567890123456789012345678901234567890   Line added to show where 60 is
Shankle drumstick corned beef, chuck turkey chicken pork
chop venison beef strip steak cow sausage. Tail short loin
shoulder ball tip, jowl drumstick rump. Tail tongue ball tip
meatloaf, bresaola short loin tri-tip fatback pork loin
sirloin shank flank biltong. Venison short loin andouille.
like image 821
selbie Avatar asked Jul 31 '11 19:07

selbie


People also ask

How do you separate a multi line in C language?

We can write multiline macros like functions, but for macros, each line must be terminated with backslash '\' character.

How do you define a long string?

Long strings can be written in multiple lines by using two double quotes ( “ “ ) to break the string at any point in the middle.

How do you write printf in two lines?

AFAIK, there's two ways to broke a long printf statement into multiple lines: One is what Viorel_ suggests, concatenate multiple strings together, one on each line. And another way is to use a backslash as the last character, something in this format: printf("part1 \ part2 \ part3");

How do you make a multiline string in C++?

By enclosing a string in quotes, we can split it across many lines. Brackets can be used to split a string into numerous lines. Furthermore, the backslash character in C++ is used to continue a line.


1 Answers

I think what you may be looking for is:

char temp[60];
int cnt, x = 0;
do
{
    cnt = 59;
    strncpy(temp, src + x, 60); //Assuming the original is stored in src
    while(temp[cnt] != ' ') cnt --;
    temp[cnt] = (char) 0;
    x += cnt + 1;
    printf("%s\n", temp);
}while (x < strlen(src));
like image 191
Ram Avatar answered Oct 28 '22 06:10

Ram