gpt4 book ai didi

c - 强制 printf 忽略格式

转载 作者:太空宇宙 更新时间:2023-11-04 05:51:40 25 4
gpt4 key购买 nike

我正在使用 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 转换为字符串,遍历该字符串,并在每个% 后面插入一个%。但是,当我一次移动很多行时(我试图创建屏幕“向上”移动的效果),这可能不是性能方面的最佳解决方案,对吗?

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

最佳答案

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

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

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

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

请注意,长度参数必须是 int 类型。

关于c - 强制 printf 忽略格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39949473/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com