【问题标题】:Why Null character does not adds up to the end of string when scanf'd?为什么空字符在scanf'd时不会加到字符串的末尾?
【发布时间】:2014-05-18 16:20:04
【问题描述】:
--start of snip--
char name[15];
...

printf("Enter employee name \n");
scanf("%s",name);

printf("strlen %d \n", strlen(name));
--end of snip --

Output:
Enter employee name
Veronica
8

为什么没有在末尾添加空字符!?我错过了什么吗?

请人解释一下。

已编辑:

正在使用 fgets 从打开的文件中读取行并使用 strtok(line,"\t ") 从线路中获取令牌。

--snip--
char * chk;
char line[100];
char temp_name[15];
while(fgets(line, sizeof line, filep))
{
      chk = strtok(line, " \t");
      while(chk !-= NULL)
      {
           strcpy(temp_name, chk);
           chk = strtok(NULL, " \t");
      }
}
--snip --

问题:

我猜测由于 strtok 定界符使用不当处理,额外字符被添加到 temp_name(不仅仅是名称)的末尾。

解决方案:

if(!strncmp(temp_name, name, strlen(name))) // this is one fix

其他用途

sscanf(line, "%s", temp_name); //easy fix

无论如何,我很困惑是否在 strtok 操作中添加了 NULL 或额外字符。

感谢您的回答。

此外,如果有人想帮助我应该在 strtok 中使用什么分隔符来避免任何空格、制表符等。

【问题讨论】:

  • 它就在那里。 strlen 不算。
  • 如果不存在,strlen 将无法测量字符串
  • 还要小心scanf。如果 usr 输入超过 15 个字符的字符串会怎样?
  • @Johnny 堆栈溢出会发生,我需要在那里修复,对吧!?或者除了检查之外还有什么更好的方便的解决方案!?

标签: c string strtok strlen


【解决方案1】:

添加了 NUL 终止符,但 strlen 返回不带 NUL 终止符的字符串长度。

【讨论】:

    【解决方案2】:

    来自man 3 strlen

    strlen()函数计算字符串s的长度,不包括 终止的空字节('\0')

    【讨论】:

      【解决方案3】:

      它在那里,Null 将在 scanf 的末尾添加到数组中。 strlen 函数将为您提供直到 NULL 的字符数。在字符串长度计算期间它不计算 NULL

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-04-26
        • 2020-07-15
        • 1970-01-01
        • 2023-03-29
        • 1970-01-01
        • 1970-01-01
        • 2021-02-28
        相关资源
        最近更新 更多