擴大您的q1
緩衝區的大小。 scanf("%s", q1)
沒有足夠的空間來存儲輸入。請記住C使用空字符'\0'
來終止字符串。如果你不考慮這個問題,緩衝區可能會溢出到其他內存中,導致undefined behavior。在這種情況下,它可能會覆蓋分配給name
的內存,因此name
最終會指向「\ 0ick」。這導致printf(%s)
,它尋找'\0'
知道什麼時候停止打印,認爲字符串比實際短。
代碼工作完美,如果你擴大緩衝區:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
char name[50];
char q1[50];
printf(" What is your name?\n");
scanf("%49s", name);
printf(" Hi %s, Do you want to have some fun? [Y/N]\n",name);
scanf("%49s",q1);
if(strcmp(q1,"Y") == 0||strcmp(q1,"y")==0)
{
printf("Awesome, let's play!\n");
}
else
{
printf("Fine");
}
printf("So %s, it's time to get started\n", name);
getchar();
return 0;
}
輸出:
What is your name?
Nick
Hi Nick, Do you want to have some fun? [Y/N]
y
Awesome, let's play!
So Nick, it's time to get started
請注意,我已經添加了預選賽%49s
避免緩衝區溢出這樣的。
你也可以完全通過改變char q1[50]
和scanf("%49s")
簡單char q1
和scanf("%c%*c", &q1)
(注意操作員「的地址」,因爲q1
不再是一個指針)規避另一個字符串的需要。
你甚至可能會從中獲得性能上的提升(儘管很小),因爲字符串是臭名昭着的內存佔用者。比較單個字符通常比比較字符串更受歡迎。
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
char name[50];
char q1;
printf(" What is your name?\n");
scanf("%49s%*c", name);
printf(" Hi %s, Do you want to have some fun? [Y/N]\n",name);
scanf("%c%*c",&q1);
if(q1 == 'Y' || q1 == 'y')
{
printf("Awesome, let's play!\n");
}
else
{
printf("Fine");
}
printf("So %s, it's time to get started\n", name);
getchar();
return 0;
}
if(q1 == 'Y' || q1 == 'y')
{
printf("Awesome, let's play!\n");
}
else
{
printf("Fine");
}
printf("So %s, it's time to get started\n", name);
getchar();
return 0;
}
如果你走這條路,你必須忽略使用格式說明%*c
因爲按回車發送一個關鍵流和回車鍵。
是什麼'q1'限制與
scanf()
輸入的長度,恰好? –'scanf(「%s」,name);' - >'scanf(「%49s」,name);' –
我加了'char q1 [50];'它正在爲我工作。 – moffeltje