-4

Please help me with this obviously silly mistake

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<ctime>

int main()
{

    srand((unsigned)time(NULL));
    int No_of_Q = 0;            //number of questions 
    int m1, m2, ans;            //two operands and answer
    int ra = 0;                 //number of right answers
    int wa = 0;                 //number of wrong answers
    char c = 'y';               //whether to continue

    printf("Let's play multiply!\n");
    do 
    {
        printf("How many questions would you like to attempt? ");
        scanf_s("%d", &No_of_Q);
        printf("\n");

        for(int i=1; i<=No_of_Q; i++)
        {
            m1=(rand()%10 + 1);
            m2=(rand()%10 + 1);

            printf("\nWhat is %d x %d = ", m1, m2);
            scanf_s("%d",&ans);

            if(ans== m1*m2)
            {
               printf("Your answer is correct!\n");
               ra++ ;
            }
            else{
            printf("Wrong, the correct answer is %d.\n", m1*m2);
            wa++ ;
            } 
        }
        printf("\n\nOut of %d answers, %d were correct and %d wrong.\n",No_of_Q, ra, wa);
        if(wa==0)
            printf("Congratulations!\n");
        else
            printf("Better luck next time!\n");
        printf("Continue game? ");
        scanf_s("%c", &c );      /*-------CANNOT GET THIS TO PERFORM--------------*/
        //printf("%c",c);
    }
      while(c=='y');

      return 0;
}

I am using vs 2012 express edition. I cannot get my program to scan answer to continue at the end of the program. The while statement at the end doesn't compute. Please help.

4

2 回答 2

0

问题是您的行scanf_s("%d", &ans);最多读取但不包括数字后的换行符。然后scanf_s("%c", &c);读取换行符,它不是'y',所以循环失败。

这就是为什么您会发现很多人(包括我自己)建议使用 阅读响应,fgets()然后使用sscanf_s().

您还应该检查scanf_s()返回正确的值(提到的两个调用为 1) - 或者返回正确的值(和fgets())。sscanf_s()fgets(line, sizeof(line), stdin) != 0sscanf_s(...) == 1)

您还应该注意这#include <ctime>是 C++ 标头;C 标头是#include <time.h>. 我看不出有任何用处#include <conio.h>,所以你可以省略它。


此外,您scanf_s()在使用%c转换时打错了电话。正如BluePixy在评论中指出的那样,您应该在 1 之后传递长度&c

if (scanf("%c", &c, 1U) != 1)
    ...oops...

C11 (ISO/IEC 9899:2011) 附录 K 涵盖了边界检查接口并且说的差不多。

于 2013-08-11T11:47:38.393 回答
0

使用scanf_s("%c", &c );函数两次而不是一次。第一个将获取'\n' 字符,然后将其替换为您的输入。

printf("Continue game? ");
scanf_s("%c", &c );      /*-------WILL GET '\n'--------------*/
scanf_s("%c", &c );      /*-------WILL ASK FOR INPUT--------------*/
于 2013-08-11T13:47:15.467 回答