gpt4 book ai didi

无法确定字符串末尾的字符值

转载 作者:行者123 更新时间:2023-12-04 09:39:30 26 4
gpt4 key购买 nike

我是 C 编程的新手。我正在尝试制作一个需要一些简单输入的程序。但是我发现,在将我的输入字符串与用户“打算”输入的内容进行比较时,末尾有一个额外的字符。我认为这可能是 '\0' 或 '\r' 但事实似乎并非如此。这是我的代码片段:

char* getUserInput(char* command, char $MYPATH[])
{
printf("myshell$ ");
fgets(command, 200, stdin);
printf("%u\n", (unsigned)strlen(command));

if ((command[(unsigned)strlen(command) - 1] == '\0') || (command[(unsigned)strlen(command) - 1] == '\r'))
{
printf("bye\n");
}

return command;
}

代码显示,进入时,说“退出”即输入5个字符。但是我似乎无法弄清楚最后一个的身份。 “再见”从不打印。有谁知道这个神秘人物可能是什么?

最佳答案

神奇的第 5 个元素很可能是换行符:\n

来自 man fgets() (我强调):

fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A '\0' is stored after the last character in the buffer.

为了证明这一点,打印出每个读取的字符:

char* getUserInput(char* command, char $MYPATH[])
{
printf("myshell$ ");
fgets(command, 200, stdin);
printf("%u\n", (unsigned)strlen(command));

{
size_t i = 0, len = strlen(command);
for (;i < len; ++i)
{
fprintf(stderr, "command[%zu]='%c' (%hhd or 0x%hhx)\n", i, command[i], command[i], command[i]);
}
}

...

关于无法确定字符串末尾的字符值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19374368/

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