【问题标题】:fgets() function can't accept message from command promptfgets() 函数无法接受来自命令提示符的消息
【发布时间】:2014-03-13 15:45:05
【问题描述】:

我正在尝试制作一个 C 程序,提示用户从控制台输入一条消息,然后显示用户输入的这条消息,如下例所示:

C:>promptTest
type your message >>>>  test
typed :  test

C:>

这是我的代码:

#include <stdio.h>
#include <string.h>
int main(){
    char msg[32];
    printf("type your message >>>>\t");
    fgets(msg,sizeof(msg),stdin);
    msg[strlen(msg) - 1] = '\0';
    printf("typed :  %s\n",msg);
    return 0;
}

它可以在Windows7和CentOS上构建,并且可以像上面一样在Windows上正常运行。

但是,它不能在 CentOS 上运行。我的意思是什么都不接受来自提示的任何消息,如下所示:

$ ./promptTest
type your message >>>>  test

typed :  
$ 

我该如何解决这个问题?

这是关于我的机器的信息。

$ cat /etc/redhat-release
CentOS release 6.4 (Final)
$ 
$ arch
x86_64
$ 

【问题讨论】:

  • 在 CentOS 中为我​​工作。您是否在两者中使用相同的来源?意味着在 Windows 中的第一个输出中,例如 ### buf =,而您在 centOS 中的尝试输出不同,例如 ### buf(1) =
  • 示例文本错误,我编辑了它。
  • 您的代码仍然与示例输出不对应。
  • strlen() 返回 size_t,但带有 %d 的 printf 需要 int。
  • @opd 不,应该是buf[strlen(buf)]。我猜 OP 想删除 '\n'。

标签: c centos fgets


【解决方案1】:

strlen() 返回 size_t 而不是 int。

在 64 位 IXish 系统上使用 %d 打印 size_t 可能会失败,因为前者最有可能是 64 位,而后者需要 32 位。

所以至少在 64 位 IXish 系统上而不是

printf("### buf(%d) = %s\n",strlen(buf),buf);
printf("### message(%d) = %s\n",strlen(message),message);

做

printf("### buf(%zu) = %s\n",strlen(buf),buf);
printf("### message(%zu) = %s\n",strlen(message),message);

作为一种(丑陋的)解决方法,您还可以将 strlen() 转换为 int。

printf("### buf(%d) = %s\n", (int) strlen(buf),buf);
printf("### message(%d) = %s\n", (int) strlen(message),message);

但是,此解决方法假定没有字符串比 INT_MAX 更长。

【讨论】:

  • 对不起,我绑定了你的代码,但它不起作用。没有接受消息。
  • 使用符号(选项-g)为 gcc 编译,然后使用调试器 (gdb) 运行代码以查看真正会发生什么。
  • 您可能希望通过添加选项-Wall -Wextra -pedantic来启用所有警告。
  • 显示unused parameter ‘agrc’,unused parameter ‘argv’和Control may reach end of non- void function
  • 我厌倦了删除这些警告。我编辑了问题中的代码。现在没有任何警告。
【解决方案2】:

我找到了解决办法。

CL+LF 引起了这件事。

见Controlling prompt for command line

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-12
    • 1970-01-01
    相关资源
    最近更新 更多