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

标签 c string

我是 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/

相关文章:

c - 我无法删除字符串中的空格

c - 安装 cmocka 时如何处理 Mac OS X 上的 RPATH 问题?

java - 知道字符串中确定位置的数字 - Java

c - 使用指针 : program that checks if strings are in lexicographical order

c - 程序两次打印出相同的打印语句

ruby - 为什么哈希的字符串键被卡住?

c++ - std::string 在 C++11 中是否总是以空值结尾?

java - 将字符串拆分为用户所需的字符数

java - 是否可以通过android studio中的字符串变量处理R.array.string-array-name?

c - 用 C 语言制作 shell