c - 为什么扫描时空字符不会添加到字符串末尾?

标签 c string strtok strlen

--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 ") 从线路中获取 token 。

--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 中使用什么分隔符以避免任何空格、制表符等。

最佳答案

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

关于c - 为什么扫描时空字符不会添加到字符串末尾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23724133/

相关文章:

c++ - 字符串到 vector 的转换抛出 std::bad_alloc

java - Libgdx 如何显示文本?

c - strtok() 在 C 中给出段错误

c - 尝试与strtok类似的拆分和存储数组

c - "Semantic issue: Implicitly declaring library function ' malloc ' with type ' void *(无符号长)'"

c++ - 函数原型(prototype)/定义

c - C 中的 If 语句输出无效

c - C 中 strtok 段错误后的 strcpy

java - 以增量方式生成随机数

c - 在 strtok() -C 的输出上使用 strcmp()