使用 C 中的 glib 函数获取交互式输入
我正在编写 ac 库,但在我想测试功能之前。因此,我执行以下操作:
int main(void)
{
GString *msg = NULL;
msg = g_string_sized_new(256);
printf ("Insert a string (255 characters at most): ");
do_fgets((char *) msg->str, (size_t) msg->len, stdin);
printf("msg->allocated_len = %u \n", (size_t) msg->allocated_len);
printf("msg->len = %u \n", (size_t) msg->len);
return 0;
}
编译正常,但程序打印以下内容: 消息->allocated_len = 512 msg->len = 0
这是为什么呢?有没有其他方法可以使用 glib 函数从用户那里获取交互式输入?
如果有人能帮助我,我将不胜感激!
I am writing a c library but before I want to test the functions. So, I do the following:
int main(void)
{
GString *msg = NULL;
msg = g_string_sized_new(256);
printf ("Insert a string (255 characters at most): ");
do_fgets((char *) msg->str, (size_t) msg->len, stdin);
printf("msg->allocated_len = %u \n", (size_t) msg->allocated_len);
printf("msg->len = %u \n", (size_t) msg->len);
return 0;
}
the compile is ok, but the program prints the following:
msg->allocated_len = 512
msg->len = 0
Why this? Is there any other way to get interactive input from the user using glib functions?
I'll be grateful if somebody could help me!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
无论如何,我假设
do_fgets
是您自己的包装fgets
的函数...您的代码失败,因为它试图读取 0 个字节(
fgets 的初始值>msg->len
)。此外,msg->len
永远不会更新(它通过值传递给do_fgets
)。I'm assuming the
do_fgets
is your own function wrappingfgets
, anyway...Your code is failing since it is trying to read 0 bytes (the initial value of
msg->len
). Additionally,msg->len
is never updated (it is passed todo_fgets
by value).复活!
我想我已经找到了我的问题的解决方案。我所做的是将输入读取到缓冲区,然后将缓冲区分配给结构成员 src ,一切正常。代码大致如下:
所以它打印出:
唯一奇怪的是为什么 allocate_len 是 512 而不是 256。
谢谢大家的回复...
Resurection!
I think I've found the solution to my question. What I did is to read the input to a buffer and then assign the buffer to the struct member src an everything is ok. That's the code roughly:
So it prints out:
The only strange is why the allocated_len is 512 instead of 256.
Thanks to everyone for the reply...
复活,调试引导我找到了下一个解决方案。谢谢Hasturkun的帮助,我从昨天开始就想发布我的答案,但新成员在8小时内无法回答他们的问题。解决方案是这样的:
它可以很好地打印出所有内容......
谢谢大家的意见!
Resurrection, debugging led me to the next solution. Thank you Hasturkun for your help, I wanted to post my answer since yesterday but new members cannot answer their questions before 8 hours pass. The solution is this:
And it prints out everything very well...
Thank you all for your comments!