题目:
编写一个程序,把较长的输入行“折”成短一些的两行或多行,折行的位置在输入行的第n列之前的最后一个非空格符之后。要保证程序能智能地处理输入行很长以及在指定的列前没有空格或制表符的情况。
补充(2021.10.26): 参考了书中的答案之后,这个题目的理解是:折行的位置在输入行的第n列之前的最后一个空格符之后,并且暗含着把输入行中的Tab扩展成空格去处理
自我解答:
题目理解:本题想要实现的是类似于Windows下txt中的自动换行功能,换行时不能分割一个完整的单词。具体行为可以在txt中打开自动换行功能,通过改变显示框的大小进行查看。(并非完全按照题目本来意思去理解)
举例如下:假设n设置为10,即每一行中最多有10个字符。下面例子中用_来表示空格
情形一:
abcdefghijklmnop 此时第10列之前没有空格,则在第10列位置即j后进行折行。自动折行后为:
abcdefghij
klmnop
情形二:
abcd_efghijk 此时第10列位置为i,此时i在单词内部,所以不能在i之后进行折行。这时的折行位置在e之前,效果为:
abcd_
efghijk
情形三:
abcd_ _ _ _ _ _ _ _efg 此时第10列是_,依然在_之后进行折行,效果为
abcd_ _ _ _ _ _
_ _efg
情形四:
abcd\tefghijk,假设\t占8个字符,第10列的字符是f,在单词内部,折行后效果为
abcd\t
efghijk
情形五:
abcdefgh\t\tijk,第9、10列的字符都为\t,此时在\t之后换行,换行效果为:
abcdefgh\t
\t
ijk
#include <stdio.h>
#define TABSIZE 8
#define N 10 //line feed for every N characters
void printLine(char s[], int len)
{
int counter;
s[len] = '\n';
s[len + 1] = '\0';
printf("%s", s);
for(counter = 0; counter < N + 1; counter++)
s[counter] = '\0';
}
int main()
{
int c, tempchar;
int pos;
char line[N + 2] = {'\0'};
int currentLen = 0;
int j = 0;
int spacePos;
int counter;
char wordchar[N] = {'\0'};
for(pos = 1; (c = getchar()) != EOF; pos++)
{
line[j++] = c;
currentLen++;
if(c == '\n')
{
printLine(line, j-1); /* print and reset */
j = 0;
currentLen = 0;
pos = 0;
continue;
}
else if(c == '\t')
{
currentLen = currentLen + TABSIZE - (pos - 1) % TABSIZE - 1;
pos = pos