[英]Program keeps on crashing
I don't know why this program doesn't work: 我不知道为什么该程序不起作用:
char syze;
printf("Please enter your desired size (Choose from S,M,L,XL)\n");
scanf("%s", &syze);
if(syze =='S')
{printf("Available");}
else if(syze =='M')
{printf("Available");}
else if(syze =='L')
{printf("Available");}
else if(strcmp(syze,"XL")==0)
{printf("Available");}
else
{printf("Please enter a valid character");}
return 0;
The problem is in 问题出在
scanf("%s", &syze);
in your code, size
is of type char
and you should be using %c
format specifier to scan the input. 在您的代码中, size
为char
类型,您应该使用%c
格式说明符来扫描输入。
If you use %s
format specifier to scan the input for a char
, essentially you'll be overrunning the allocated memory thereby creating undefined behaviour 如果您使用%s
格式说明符来扫描输入中的char
,那么实际上您将超出分配的内存,从而产生未定义的行为
Then, 然后,
strcmp(syze,"XL")
is also wrong, as strcmp()
needs a ( const
) char *
as both the arguments, and you're passing a char
as the first one. 这也是错误的,因为strcmp()
需要将( const
) char *
作为两个参数,并且您将char
作为第一个参数传递。 You can simply make use of the equality operator, ==
to compare a char
. 您可以简单地使用等于运算符==
比较char
。
Finally, a char
will never be able to hold "XL"
. 最后,一个char
将永远无法容纳"XL"
。
Solution: If you need to have "XL"
as one of the inputs, you may want to change syze
to an array, like 解决方案:如果需要将"XL"
作为输入之一,则可能需要将syze
更改为数组,例如
char syze[3] = {0};
or likewise. 或同样。 In that case, you can keep the scanf()
as 在这种情况下,您可以将scanf()
保留为
scanf("%2s", syze);
and compare your inputs using strcmp()
. 并使用strcmp()
比较您的输入。
You have a problem in strcmp(syze,"XL")==0
. 您在strcmp(syze,"XL")==0
遇到问题。 You can't compare a char
to a string XL
. 您不能将char
与字符串XL
进行比较。 Use only X
for that choice and compare the same as the others if(syze =='X')
. 对于该选择仅使用X
并与其他if(syze =='X')
。
You have another problem in scanf("%s", &syze);
您在scanf("%s", &syze);
还有另一个问题scanf("%s", &syze);
. 。 Use %c
to scan a char
: 使用%c
扫描char
:
scanf("%c", &syze);`
If you want to keep using the choice "XL", you should declare syze
as char syze[3]
and compare all choices using strcmp
. 如果要继续使用选项“ XL”,则应将syze
声明为char syze[3]
并使用strcmp
比较所有选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.