Scanf_s不断返回\\ 0,而不是输入 [英] Scanf_s keeps returning \0 instead of input

查看:359
本文介绍了Scanf_s不断返回\\ 0,而不是输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经成为停留在一,在我心里,pretty简单的任务。我写了选取一个随机数的程序,而且让你猜是,如果输入字符'n'或'N'末退出方案,其中之一。
在code是如下:

I've become stuck on a, in my mind, pretty simple task. I have written a program that picks a random number, and makes you guess which one it is and exit the program at the end if the characters 'n' or 'N' is entered. The code is as follows:

#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 而不是我输入字符。我已经发现的问题还是我错了?我可以更改为解决这个问题?

The problem I'm having is that my last scanf_s gives me \0 instead of the character i enter. Have I identified the problem or am I wrong? What can I change to remedy this problem?

推荐答案

您最近 scanf_s 接收 \\ n 和没有 \\ 0 。吃了这个 \\ n 更改

Your last scanf_s receives \n and not \0. To eat up this \n change

printf("Ska vi spela en g\x86ng till(J/N)? ");
scanf_s("%*c%c", &keepGoing);

 printf("Ska vi spela en g\x86ng till(J/N)? ");
 scanf_s(" %c", &keepGoing);
          ^
          |
   space before %c specifier

这是工作。结果
输出:Win7上使用GCC 4.7.1

It is working.
Output: On Win7 with GCC 4.7.1

这篇关于Scanf_s不断返回\\ 0,而不是输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆