以下问题是否因空字符而发生。 “是/否”。请解释原因。
第一个代码
#include<stdio.h>
struct date{ char day[2]; char month[2]; char year[4];
}current_date;
void main(){
printf("Enter day: ");
scanf("%s",current_date.day);
printf("Enter month: ");
scanf("%s",current_date.month);
printf("Enter year: ");
scanf("%s",current_date.year);
printf("\nEntered date is:
%s/%s/%s",current_date.day,current_date.month,current_date.year)
}
输入:
如果我每次扫描时分别输入17,02,1998。
输出:
Entered date is: 17021998/021998/1998
当我只是更改结构中的数组长度时,第二个代码用于相同的输入。
#include<stdio.h>
struct date{ char day[3]; char month[3]; char year[5];
}current_date;
其余整个代码是相同的。
输出
Entered date is: 17/02/1998
请解释一下。预先感谢您!
最佳答案
在 c ,字符串不是内在类型。 C 字符串约定具有一维字符数组,该数组以空字符('\0'
)结尾。
使用应该使用的知识
struct date{ char day[3]; char month[3]; char year[5];
否则scanf
1将无法存储\0
内 数组,如果您尝试获取 2
位输入(对于 day
或 month
或 4
数字年份(使用 %s
格式说明符) - 因为 scanf
会尝试将其写入数组之外,这将是 Undefined Behaviour .
scanf
的用法是
if(scanf("%2s",current_date.day)!=1){
fprintf(stderr,"Error in input\n");
exit(EXIT_FAILURE);
}
您定义结构的方式 - 如果您存储相应的值,将为您提供 1
数字月份、1
数字日期和 3
数字年份\0
也。那不是你想要的。在 C
中,字符串是使用 nul 终止的 char
数组实现的 - scanf
存储它们。这就是为什么在我的例子中我使用了 %2s
- 这样剩余的空间就可以用来存储 \0
。
1 这里请注意 reference 中的一件事在 %s
格式说明符
matches a sequence of non-whitespace characters (a string) If width specifier is used, matches up to width or until the first whitespace character, whichever appears first. Always stores a null character in addition to the characters matched (so the argument array must have room for at least
width+1
characters).
注意:正如 Simon Berthiaume 在评论中指出的那样 -
You can write string length like this:
char year[4+1];
, that way it is clear what the content size is intended to be. For example in this case it is 4 digit year that you wanted.
关于c - C 语言中字符串的结构空字符(\0) 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48842085/