在我看来,我已经陷入了一项非常简单的任务。我写了一个程序,它选择一个随机数,让你猜测它是哪个,如果输入了字符“n”或“N”,最后退出程序。代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int input_switcher(int input, int answer)
{
if (input == answer) {return 1;}
else if(input < answer) {return 2;}
else if(input > answer) {return 3;}
else {return 0;}
}
int main(void)
{
int input, answer, tries;
char keepGoing = 'J';
srand((int)time(0));
while(42)
{
input = 0, tries = 0;
answer = 1;//rand()%100+1;
printf("Jag \"t\x84nker\" p\x86 ett tal mellan 1 och 100, gissa vilket!\n");
while(42)
{
printf("Gissning: ");
scanf_s("%d", &input);
switch (input_switcher(input, answer))
{
case 1:
printf("Grattis, det var r\x84tt!\n");
printf("Du gjorde %d f\x94rs\x94k.", tries);
break;
case 2:
printf("Du gissade f\x94r l\x86gt, f\x94rs\x94k igen!\n");
tries++;
break;
case 3:
printf("Du gissade f\x94r h\x94gt, f\x94rs\x94k igen!\n");
tries++;
break;
default:
break;
}
if(input == answer) {break;}
}
printf("Ska vi spela en g\x86ng till(J/N)? ");
scanf_s("%*c%c", &keepGoing);
if(keepGoing == 'N' || keepGoing == 'n') {return 0;}
else if(keepGoing == 'J' || keepGoing == 'j') {system("cls");}
}
return 0;
}
我遇到的问题是我的最后一个scanf_s
给了我\0
而不是我输入的字符。我发现了问题还是我错了?我可以改变什么来解决这个问题?