为什么在扫描时空字符不会加到字符串的末尾? [英] Why Null character does not adds up to the end of string when scanf'd?

查看:49
本文介绍了为什么在扫描时空字符不会加到字符串的末尾?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

why is it not adding null character to the end !? am i missing anything?

请人解释一下.

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

Was reading line from opened file using fgets and used strtok(line,"\t ") to get the tokens from the line.

--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 分隔符使用不当处理不当,临时名称(不仅仅是名称)的末尾添加了额外的字符.

I am guessing extra character is getting added to the end of the temp_name(not just the name) due to improper handling in strtok delimitter usage.

解决方案:

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

其他明智的使用

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

无论如何,我很困惑在 strtok 操作中是否存在 NULL 或额外字符的问题.

Anyways I was confused whether there is problem with NULL or extra character getting added to in strtok operation.

感谢您的回答.

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

Further, if any one would like to help out what delimiter should i use in strtok to avoid any space, tab etc.

推荐答案

添加了 NUL 终止符,但 strlen 返回的字符串的长度没有其 NUL 终止符.

The NUL terminator character is added, but strlen returns the length of the string without its NUL terminator.

这篇关于为什么在扫描时空字符不会加到字符串的末尾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆