我是c的新手,我正在尝试打字游戏。但if语句不起作用,输出“退出非零状态”。可能问题是由于IDE,我无法理解,谢谢。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main (void)
{
char start;
printf ("here is a typing game\n");
printf ("type any key to start\n");
scanf ("%c", &start);
void game()
{
int i;
char answer;
char type[20];
{
for (i = 0; i < 20; i++)
{
printf ("%c", 'a' + (random() % 26));
}
}
scanf ("%s", answer);
if (strcmp(answer,type) == 0)
{
printf ("good\n");
}
else
{
printf ("so bad\n");
}
}
game();
}
答案 0 :(得分:1)
此代码存在许多问题。
您不能在其他功能中使用某个功能(与game
中定义的main
一样)。
answer
是单个char
,而不是字符串,因此要使用scanf
阅读它,您需要使用行scanf("%c", &answer);
- 如果您想要的话是读一个字,即;在其余代码中,您似乎希望answer
成为字符串,因此您必须将答案声明为char [20]
数组,并使用{{1}调用scanf
格式说明符。
您无法使用"%s"
将strcmp
与字符串进行比较。 char
用于将字符串与字符串进行比较,而不是将字符串与字符或字符与字符进行比较。此外,您永远不会在代码中的任何位置为数组strcmp
分配字符串。
答案 1 :(得分:0)
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void game();
int main (void)
{
char start;
srand(time(NULL));//seed rand function with time to generate "near to pseudo random numbers"(note: This is not "really" pseudo anyways!)
printf ("here is a typing game\n");
printf ("type any key to start\n");
scanf("%c",&start);
//define your function outside main
game();//call your function here
}
void game()
{
int i;
char answer[20];//answer should also be an array
char type[20]="";//initialize type this way to avoid unnecessary characters initialization
{
for (i = 0; i < 19; i++)//should be 19 not 20... Last character has to be null
{
printf ("%c", type[i]='a' + (rand() % 26));//You forgot to add the random characters in type array and
//rand should be called this way
}
}
scanf ("%s", answer);
if (strcmp(answer,type) == 0)
{
printf ("good\n");
}
else
{
printf ("so bad\n");
}
}
建议:仍然应该进行即兴创作,例如使用fgets()获取输入而不是scanf并在输入处管理应答数组溢出。