[英]scanf catches char type string with \0 and bunch of zeros after in C
I'm working on enumerations in C and can't find the source of problem in the following example that, the output is always "Sorry!": 我正在使用C进行枚举,在以下示例中找不到问题的根源,即输出始终为“对不起!”:
#include <stdio.h>
#include <stdlib.h>
typedef enum
{
summer, winter, fall, spring
} season;
void printPhrase (season s);
int main(void)
{
printf("What's your prefered season? ");
char seasonHold[10], seasonHold2[10];
scanf("%s", seasonHold);
for (int n = 0; n < strlen(seasonHold); n++)
{
if (n != '\0')
seasonHold2[n] = seasonHold[n];
}
printPhrase (*seasonHold2);
return 0;
}
void printPhrase (season s)
{
if (s == summer)
printf("It's hot out!\n");
else if (s == fall)
printf("It's getting cooler!\n");
else if (s == winter)
printf("Should be really cold!\n");
else if (s == spring)
printf("It should be lovely outside!\n");
else
printf("Sorry!\n");
}
The problem is whatever input I enter, there's always one output: Sorry! 问题是无论我输入什么输入,总会有一个输出:对不起! Thanks.
谢谢。
Also, this can solve the matter: I could manage it by changing main function into following: 此外,这可以解决问题:我可以通过将主要功能更改为以下内容来对其进行管理:
int main(void)
{
printf("What's your prefered season? ");
char seasonHold[10];
scanf("%s", seasonHold);
if (seasonHold[0] == 's')
printPhrase (summer);
else if (seasonHold[0] == 'f')
printPhrase(fall);
else if (seasonHold[1] == 'p')
printPhrase(spring);
else if (seasonHold[0] == 'w')
printPhrase(winter);
return 0;
}
Enums are like constant integers. 枚举就像常量整数。 Here: summer=0, winter=1,...
此处:夏季= 0,冬季= 1,...
seansonhold is a char*. seansonhold是一个字符*。 By dereferencing it you get a char.
通过取消引用它,您得到一个字符。 This char will then be converted to a 'season' type because char->int does not give compiler errors.
然后,由于char-> int不会给出编译器错误,因此此char将被转换为'season'类型。
So you basically test here if the first byte of your char array is equal to 0,1,2.. 因此,您基本上在这里测试char数组的第一个字节是否等于0,1,2。
If you are sure seasonHold is null-terminated (it will be here), you can use a pointer and while loop to accomplish what you want: 如果您确定seasonHold是空终止的(它将在此处),则可以使用指针和while循环来完成所需的操作:
char *ptr = seasonHold;
n = 0;
while (*ptr++) { /* same as saying while (*ptr++ != '\0') */
seasonHold2[n] = seasonHold[n]; /* could also do: seasonHold2[n] = *ptr; */
n++;
}
seasonHold2[n] = 0; /* null-terminate */
Additionally, if you would like to dynamically allocate seasonHold2
, you can simply declare it as a pointer, include string.h
and use strdup
to copy seasonHold
to seasonHold2
, eg: 另外,如果您想动态分配
seasonHold2
,则可以简单地将其声明为指针,包括string.h
并使用strdup
将seasonHold
复制到seasonHold2
,例如:
#include <string.h>
...
char *seasonHold2;
...
seasonHold2 = strdup (seasonHold);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.