自动换行程序C

自动换行程序C,c,word-wrap,C,Word Wrap,在C编程语言第1章的末尾,有一些练习需要完成。我现在正在做的一个任务是制作一个程序,将一个长字符串以特定的长度包装成多行。下面的函数100%工作,除了最后一行没有被包装外,不管指定的行的最大宽度是多少 // wrap: take a long input line and wrap it into multiple lines void wrap(char s[], const int wrapline) { int i, k, wraploc, lastwrap; lastw

在C编程语言第1章的末尾,有一些练习需要完成。我现在正在做的一个任务是制作一个程序,将一个长字符串以特定的长度包装成多行。下面的函数100%工作,除了最后一行没有被包装外,不管指定的行的最大宽度是多少

// wrap: take a long input line and wrap it into multiple lines
void wrap(char s[], const int wrapline)
{
    int i, k, wraploc, lastwrap;

    lastwrap = 0; // saves character index after most recent line wrap
    wraploc = 0; // used to find the location for next word wrap

    for (i = 0; s[i] != '\0'; ++i, ++wraploc) {

        if (wraploc >= wrapline) {
            for (k = i; k > 0; --k) {
                // make sure word wrap doesn't overflow past maximum length
                if (k - lastwrap <= wrapline && s[k] == ' ') {
                    s[k] = '\n';
                    lastwrap = k+1;
                    break;
                }
            }
            wraploc = 0;
        }

    } // end main loop

    for (i = 0; i < wrapline; ++i) printf(" ");
    printf("|\n");
    printf("%s\n", s);
}

该线表示应将其包裹的位置。在这种情况下,
wraploc
的值为14,此时明显有更多的字符

我不知道为什么会这样,有人能帮我吗


(另外,我是C语言的完全初学者,我没有使用指针的经验,因此请远离答案中的指针,谢谢)。

您使用
I
递增
wraploc
,直到到达
wrapline
(示例中为15)。
包装时,从
i
回溯到最后一个空格。
这意味着在下一行中,您在
lastwrap
位置和
i
之间已经有一些字符,即,您不能在那里将
wraploc
重置为0。

请尝试设置
wraploc=i-lastwrap

任何可能像我一样发现此问题并在源字符串中遇到新行问题的人

我的答案是:

inline int wordlen(const char * str){
   int tempindex=0;
   while(str[tempindex]!=' ' && str[tempindex]!=0 && str[tempindex]!='\n'){
      ++tempindex;
   }
   return(tempindex);
}
void wrap(char * s, const int wrapline){

   int index=0;
   int curlinelen = 0;
   while(s[index] != '\0'){

      if(s[index] == '\n'){
         curlinelen=0;
      }
      else if(s[index] == ' '){

         if(curlinelen+wordlen(&s[index+1]) >= wrapline){
            s[index] = '\n';
            curlinelen = 0;
         }

      }

      curlinelen++;
      index++;
   }

}


尝试
for(k=i-1;k>0;--k)
而不是
for(k=i;k>0;--k)
不,没有什么区别@ciphermagit谢谢!真不敢相信我竟然不认识这个事实
$ ./a.out
               |
this is a
sample string
the last line
will surely overflow
inline int wordlen(const char * str){
   int tempindex=0;
   while(str[tempindex]!=' ' && str[tempindex]!=0 && str[tempindex]!='\n'){
      ++tempindex;
   }
   return(tempindex);
}
void wrap(char * s, const int wrapline){

   int index=0;
   int curlinelen = 0;
   while(s[index] != '\0'){

      if(s[index] == '\n'){
         curlinelen=0;
      }
      else if(s[index] == ' '){

         if(curlinelen+wordlen(&s[index+1]) >= wrapline){
            s[index] = '\n';
            curlinelen = 0;
         }

      }

      curlinelen++;
      index++;
   }

}