C 编程 - 如何将 char 写入 char*

发布于 2024-12-22 15:21:30 字数 378 浏览 4 评论 0原文

C 中的几个函数可以确保将字符写入流,例如:

 int fputc ( int character, FILE * stream );
 int putchar ( int character );
 int putc ( int character, FILE * stream );
...

我的问题很简单:是否有任何函数可以将字符写入 char*? (回调(int字符,char *流)

更新 :更多地解释我的问题 我正在使用 lex/yacc 编译解决方案。
input() 函数返回流中的下一个字符。我想针对指定条件将此函数返回的整个流存储到变量中。

Writing a character to the stream is ensured by several functions in C, such as :

 int fputc ( int character, FILE * stream );
 int putchar ( int character );
 int putc ( int character, FILE * stream );
...

My question is simple : is there any function which provide the possibility to write a character into a char*? (callback(int character, char * stream))

update
:to explain more my problem
i'am using lex/yacc compiling solution.
input() funcion returns the next character in the stream .I want to store for a specified condition the whole stream returned by this function into a variable.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

残龙傲雪 2024-12-29 15:21:31

由于指针算术是 C 的本质,因此不存在这样的函数。要将一个字符放入 stream 指向的某个内存中并推进它,您可以这样做:

*stream++ = character;

在下一个序列点 stream 将指向新的、尚未写入的字符。

当然,请确保您不会将 stream 推进到超出其分配区域的范围。为了防止这种情况发生,你可以做一个简单的计算:

if (stream - base > BUFFER_SIZE) /* stop */

base将是一个指向分配区域开头的指针,即stream的初始值。

Since pointer arithmetic is in the very nature of C, there are no such functions. To put a character into some memory pointed to by stream and advance it, you would do:

*stream++ = character;

At the next sequence point stream will be pointing to the new, still unwritten character.

Of course, make sure that you don't advance stream beyond the bounds of its allocated area. To prevent this from happening you could do a simple calculation:

if (stream - base > BUFFER_SIZE) /* stop */

base would be a pointer to the beginning of the allocated area, the initial value of stream.

债姬 2024-12-29 15:21:31

为什么不直接访问指针:

*stream = character;

Why not directly access the pointer:

*stream = character;
深海夜未眠 2024-12-29 15:21:31

当然,如果您需要一个函数,请尝试 snprintf

char buffer[BUFFER_SIZE];
char c = 'x';
snprintf(buffer, sizeof buffer, "%c", c);

如果您愿意先将字符转换为字符串,您也可以使用 strcatstrcpy 等。

Sure, try snprintf if you need a function.

char buffer[BUFFER_SIZE];
char c = 'x';
snprintf(buffer, sizeof buffer, "%c", c);

If you're willinig to convert your char to a string first, you can also use strcat, strcpy etc.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文