函数自动循环?

Function automatically looping?

本文关键字:循环 函数      更新时间:2023-10-16

好的,所以这个函数应该从用户那里获取结果,然后给他们一个选项来输入更多结果或在完成后返回主菜单main((。

一切正常。 唯一的问题是在切换前的最后一个scanf语句。

而不是等待用户输入userChoice,它会自动重新启动该功能。它只应该在userChoice是"a"或"A"时才这样做,但它似乎也完全忽略了 scanf 语句和开关。我做错了什么?向下滚动以查看 im 引用的行。

void inputResults(int gameNumber, int i, int j)
{

int Results[ROWS][COLS];
char userChoice = ' ';
if (j >= COLS)
{
j = 0;
i = i + 1;
}
if (gameNumber > ROWS)
{
printf("nJk, Max number of games reachedn");
main();
}
gameNumber = gameNumber + 1;
printf("nHow many points did the home team score in game %d?n", gameNumber);
scanf_s("%d", &Results[i][j]);
j = j + 1;
printf("nHow many points did the opponents score in game %d?n", gameNumber);
scanf_s("%d", &Results[i][j]);
printf("nHome: %d  Opponents: %dn", Results[i][j-1], Results[i][j]);
printf("nA) Enter results for game %dnB) Main menu  n", (gameNumber + 1));
*************************PROBLEM***********************************
scanf_s("%c", &userChoice); /*it ignores THIS it just loops the 
function after it prints the above*/
switch (userChoice) //it doesnt even get to this.
{
case 'A':
inputResults(gameNumber, i, j);
case 'a':
inputResults(gameNumber, i, j);
case 'b':
main();
case 'B':
main();
default:
printf("nThats still not  a valid choice duden");
}
}

如果您想知道,传递给 gameNumber、i 和 j 的值都是 0。它们是从主函数传递的

当你读到一个带有类似scanf_s的字符时

char ch;
scanf_s("%c", &ch, 1);

并输入例如字母"A"并按回车键,"A"以ch结尾,但按回车键的""仍保留在标准输入中。在下次调用scanf_s()时,此""将被读取并存储在ch中,而不会给您任何输入的机会。

scanf_s("%c[^n]", &ch, 1);

相反,它将读取并丢弃仍在stdin中的所有额外字符,直到下一个换行符。