c - 实现换行的不同方式

标签 c

我正在尝试使用行长来换行并一次打印一行(行长),而不是将整行打印为一个 block 。我认为在每一行长度处添加 '\n' 字符就可以完成工作并编写了以下代码。

void wrap(char *tok, int len)
{
  int i, h;
  char *ss = tok;
  for (h = linelen; h < (len + 1); (h + linelen))
    {
      ss[h] = '\n';
      printf("%d\n", h);
      h += linelen;
    }
  char *token = strtok(ss, "\n");
  while (token)
    {
        printf("%s\n", token);
        token = strtok(NULL, "\n");
    }
}

但是这段代码似乎不起作用。还有哪些方法可以实现换行?

最佳答案

从这篇文章中被盗:Is it possible to print out only a certain section of a C-string, without making a separate substring?

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

int main(void) {

    char *str = "helo world";
    int total_len = strlen(str);
    int single_len = 3;
    for (int i = 0; i < total_len; i += single_len) {
        /* print at most first three characters (safe) */
        printf("%.*s\n", single_len, str + i);
    }

    return 0;
}

关于c - 实现换行的不同方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15852936/

相关文章:

检查 C 中的单元测试 : Best way to test static methods

c - %r 在内核 printf 格式中意味着什么?

c - 段错误处理程序中的段错误

c - 如何编译 C 程序?

c - 双端口 RAM 最佳实践?

c - C中堆栈帧的函数参数名称和变量名称?

c - 为什么 malloc 真的是不确定的? (Linux/Unix)

C 指向覆盖最后保存的指针的指针

c - 以下 C 结构如何扩展为

c - realloc 后奇怪的字符