【问题标题】:Function automatically looping?函数自动循环?
【发布时间】:2018-09-09 00:07:10
【问题描述】:

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

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

无需等待用户输入userChoice,而是自动重新启动该功能。如果userChoice 是“a”或“A”,它只应该这样做,但它似乎也完全忽略了 scanf 语句和 switch。我究竟做错了什么?向下滚动以查看我所指的行。

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 reached\n");
            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: %d\n", Results[i][j-1], Results[i][j]);
        printf("\nA) Enter results for game %d\nB) 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 dude\n");
        }

}

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

【问题讨论】:

  • can not call main() 显然是 C++ 代码中的函数......另外你正在使用 scanf_f() wrong
  • 您是用 C 还是 C++ 编程?您的整个程序都是用 C 编写的,包括对 main() 的显式调用,这在 C++ 标准中是不允许的。
  • @C.M.如何正确使用 scanf_f ?因为当我输入 scanf_f 而不是 scanf_s 时,它说函数中引用了未解析的外部符号 scanf_f
  • 一切正常。 -- 这不是合法代码。你不能直接打电话给main()
  • @MixtapeMania 你试过阅读我给你的链接吗?

标签: c++


【解决方案1】:

当你用scanf_s读单个字符时喜欢

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

然后输入例如。字母 'A' 并按回车键,'A' 以ch 结尾,但您按回车键的 '\n' 仍保留在标准输入中。在下次调用 scanf_s() 时,会读取此“\n”并将其存储在 ch 中,而不会让您有机会进行任何输入。

使用

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

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

【讨论】:

  • 谢谢,这个解决方案有效。似乎还有更多问题,但我会反复试验,它至少解决了 scan_f 问题。
猜你喜欢
  • 2021-01-17
  • 1970-01-01
  • 2021-11-26
  • 1970-01-01
  • 1970-01-01
  • 2017-10-19
  • 1970-01-01
  • 2017-04-08
  • 2019-08-08
相关资源
最近更新 更多