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