强制 printf 忽略格式

Forcing printf to ignore formatting

我正在使用 pdcurses 库,并且我正在编写一个将屏幕上的一行向上移动的函数。这涉及复制当前行,然后将其粘贴到上面。问题是用于打印整行的 curses 函数 printw 使用与 printf 相同的格式字符串。这些行可能包含百分号,因此一旦粘贴,这些符号当然会丢失。

The printw() functions add a formatted string to the window at the current or specified cursor position. The format strings are the same as used in the standard C library's printf(). (printw() can be used as a drop-in replacement for printf().)

一个小例子是:

chtype p[200]; 
winchnstr(w, p, 200); //obtain the line
clrtoeol(); //remove the line

wmove(w, y-1, x); //move up a line
clrtoeol(); //erase the line
wprintw(w, p); //print the new line

有什么方法可以强制 printf 正常处理百分号,而不必经过 p 并在每个百分号之间插入一个百分号?对于如此简单的事情,这似乎很烦人。

第一个解决方案是将p转换为字符串,遍历字符串,并在每个%后面插入一个%。但是当我一次移动很多行时(我正在尝试创建屏幕移动的效果 "upwards"),这可能不是性能方面的最佳解决方案,对吗?

另一种解决方案是遍历 p 并仅使用 addch() 分别添加每个字符。但是与wprintw相比,这会失去performance/efficiency吗?或者 wprintw 只是单独粘贴每个字符的美化版本?我真的只有这两个选择吗?

你不能简单地改变:

wprintw(w, p);

改为:

wprintw(w, "%s", p);

或者:

waddchstr(w, p);

要强制 printf 按原样接受您的字符串,请使用格式说明符 %s 并将您的字符串作为参数传递。 printf 参数不受格式处理的影响。在字符串的情况下,字节被简单地复制到目标缓冲区。

printf("%s", "My string with % signs");

如果您的字符串不是零终止的,如果您使用 %*s 格式说明符,则可以在字符串之前将长度传递给 printf:

printf("%*s", 5, "ab%cdefghi"); // prints "ab%cd"

注意长度参数必须是int.

类型

您可以使用 addstr() 而不是 printw()。 (printw() 基本上只是解析格式字符串并将结果传递给 addstr()。)