c - 不使用 printf 打印新行

标签 c printf

我当前正在使用 printf("'%.*s'\n", length, start); 打印字符串,其中 start const char* 且长度为 int

打印的字符串有时包含换行符\n,这会扰乱格式,是否可以将它们替换为字符\n打印输出中的 ,而不是 \n 字符。 如果没有,你能帮忙提供一个替换字符的函数吗?

该字符串是一个 malloc 字符串,它具有来自不同指针的其他引用,因此无法更改。

编辑:我编写了以下代码,我认为它可以满足我的需要

static void printStr(const char* start, int length) {
  char* buffer = malloc(length * sizeof(char));
  int processedCount = 0;
  for(int i = 0; i < length; i++) {
    char c = start[i];
    if(c == '\n') {
      printf("%.*s\\n", processedCount, buffer);
      processedCount = 0;
    } else {
      buffer[processedCount] = c;
      processedCount++;
    }
  }
  printf("%.*s", processedCount, buffer);
  free(buffer);
}

最佳答案

不需要分配内存来处理字符串。简单地说,迭代原始字符并根据需要打印字符。例如:

#include <stdio.h>

void print(const char * str, int length)
{
    for (int i = 0; i < length; ++i) {
        if (str[i] == '\n') {
            putchar('\\');
            putchar('n');
        } else
            putchar(str[i]);
    }
}

int main()
{
    print("hello\nworld!", 12);
    return 0;
}

关于c - 不使用 printf 打印新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50865373/

相关文章:

32 位和 64 位之间完全不同的输出

scanf 中的字符输入 ("%d", &value)

可以在标记粘贴之前扩展宏吗?

关于 malloc array of struct 的困惑

将文件内容复制到双数组

c++ - 为什么在包含 iostream 时可以使用 printf()?

c - 将用于分配内存的指针声明为 const 是否有缺点

C Socket 客户端打印出奇怪的输出

c - 有没有更好的方法来调整打印整数的缓冲区大小?

C++: "float"的 printf() 格式规范是什么?