数组和scanf函数协同工作的问题 [英] Problems with array and scanf function working together

查看:136
本文介绍了数组和scanf函数协同工作的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是初学者。我想编写一个程序,它将猜测一个用户选择的数字。通常,用户在给定的限制范围内选择一个数字,程序会在相同的限制范围内生成一个随机数,询问用户是否正确的数字,是/否答案,程序会读取该数字,然后询问用户的数目是大还是小,读取答案并将此信息传递给2个附加函数。

I am a beginner. I want to write a program, that will guess a number, which user picked. In general, user pick a number within the given limit, the program will generate a random number within same limit, ask user if it's a right number, Y/N answer, program reads it, then ask if user's number is bigger or smaller, reads the answer and pass this information to 2 additional functions.

(我尚未完成这些操作,但想法是将其余数字除以2,再问一遍,较大的较小,再将其除以2,依此类推,直到得到答案。)

(I didn't finish those yet, but the idea is that it will divide the rest of numbers in 2, ask again, bigger smaller, divide it once again by 2 and so on, till we get the answer.)

问题是,即使我使用最简单的char类型数组,也无法得到这行得通。计算机的答案是,如果我没有为其中一个数组预订足够的内存。

The problem is, that even if I use a simplest array of type char, I cannot get it work. The answer of the computer is if I didn't book enough memory for one of the arrays.

距本书中的数组主题还有2章,我只是想编写这个程序。我在这里使用的是到目前为止所学的知识,因此,如果可能的话,请不要在答案中使用C的任何更复杂的功能。

I'm still 2 chapters away from the arrays theme in my book, I just wanted to write this program. What I use here is what I've learned so far, so if it's possible, don't use any more complex functions and features of C in your answers.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <time.h>
int bigger(int number, int limit);
int lower(int number, int limit);

int main(void) {
    system("COLOR B0");
    
    const int Hlimit=100;
    const int Llimit=0;
    char alowwed_answer[]={'>','<'};
    char answer[2];
    char alowwed_answerYN[]={'Y', 'N'};
    char answerYN[2];
    srand((unsigned)time(NULL));
    int numberTOguess;
    printf("\r\nEnter your number from %i to %i, "
            "and I will try to guess!: ",Llimit,Hlimit);
    
    while(scanf("%i",&numberTOguess) )
    {
        int check=rand()%Hlimit;
        printf("\r\nyour number is - %i Y/N?",check);
        scanf("%c",&answerYN[0]);
        printf("answer is %c\r\n", answerYN);//this line is for checking;
        int check_answ=strcmp(answerYN[0],alowwed_answerYN[0]);
        printf("check answer is %i",check_answ);//this line is for checking;
        if(check_answ==0)
        {
            printf("I did it!");
            break;
        }
        else if(strcmp(answerYN[0],alowwed_answerYN[1])==0)
        {
            printf("\r\nyour number is bigger '>' or smaller '<'?: ");
            scanf("%c",&answer);
            if(strcmp(answer[0],alowwed_answer[0])==0)
            {
                bigger(check, Hlimit);
            }
            else if(strcmp(answer[0],alowwed_answer[1])==0)
            {
                lower(check, Llimit);
            }
        }        
    }
    printf("\r\nI did it!");
    return 0;
}

int bigger(int number, int limit)
{
    printf("it is bigger!");//I will finish this part as soon as I will get first part working.
    return 0;
    
}
int lower(int number, int limit)
{
    printf("it is lower!!!");//I will finish this part as soon as I will get first part working.
    return 0;
    
}


更新


谢谢,我参加了您的建议,然后将语句类型更改为SWITCH。但是它仍然无法正常工作。嵌套开关根本不起作用。

Update

Thanks, I took your advice and change the statement type to SWITCH. But it still doesn't work properly. Somehow, nested switch doesn't function at all.

查看代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <time.h>
int bigger(int number, int limit);
int lower(int number, int limit);

int main(void) {
    system("COLOR B0");
    
    const int Hlimit=100;
    const int Llimit=0;
    
    char answerBL;
   
    char answerYN;
    srand((unsigned)time(NULL));
    int numberTOguess;
    printf("\r\nEnter your number from %i to %i, "
            "and I will try to guess!: ",Llimit,Hlimit);
    
    while(scanf("%i",&numberTOguess) )
    {
        int check=rand()%Hlimit;
        printf("\r\nyour number is - %i Y/N?",check);
        scanf("%c",&answerYN);
        
        switch(answerYN)
        {
            case 'Y':
                printf("I did it!");
                break;
            case 'N':
                printf("\r\nOk, your number is bigger '>' or smaller '<'?: ");
                scanf("%c",&answerBL);
                switch(answerBL)
                {
                    case '>':
                         bigger(check, Hlimit);
                         break;
                    case'<':
                        lower(check, Llimit);
                        break;
                        
                }
            default:
                printf("Y or N?");
                
        }
        
    }
    printf("\r\nEND!");
    return 0;
}

int bigger(int number, int limit)
{
    printf("it is bigger!");
    return 0;
    
}
int lower(int number, int limit)
{
    printf("it is lower!!!");
    return 0;
    
}


编辑


问题已解决,我找到了原因以及解决方法。这是从另一个主题开始的

Edit

Problem is solved, I found the reason and how to fix it. Here it is, from another topic


基本问题是scanf()在缓冲区中的数字后留下换行符,然后用%c读取在下一关。实际上,这很好地说明了为什么我不使用scanf();我使用行读取器(例如fgets())和sscanf()。

The basic problem is that scanf() leaves the newline after the number in the buffer, and then reads it with %c on the next pass. Actually, this is a good demonstration of why I don't use scanf(); I use a line reader (fgets(), for example) and sscanf(). It is easier to control.

您可能可以通过使用 %c而不是%c用于格式字符串。空格会导致scanf()在读取字符之前跳过空格(包括换行符)。

You can probably rescue it by using " %c" instead of "%c" for the format string. The blank causes scanf() to skip white space (including newlines) before reading the character.

但是从长远来看,放弃scanf()和fscanf()会更容易,使用fgets()或同等方法加上sscanf()。除了所有其他方面,当您需要处理整个字符串时,错误报告要容易得多,而不是在scanf()失败后留下的杂物。

But it will be easier in the long run to give up scanf() and fscanf() and use fgets() or equivalent plus sscanf(). All else apart, error reporting is much easier when you have the whole string to work with, not the driblets left behind by scanf() after it fails.

您还应该始终检查一下您得到从scanf()转换的值。输入失败-例行且可怕。

You should also, always, check that you get a value converted from scanf(). Input fails — routinely and horribly. Don't let it wreck your program because you didn't check.

回答了2012年3月5日7:05

Jonathan Leffler

answered Mar 5 '12 at 7:05
Jonathan Leffler


推荐答案

函数 strcmp 应该以两个指针作为参数,指向 null的第一个字符的指针终止的字节字符串

The function strcmp expected two pointers as arguments, pointers to the first characters of a null-terminated byte strings.

带有例如

strcmp(answerYN[0],alowwed_answerYN[0]);

您有两个主要问题:

you have two major problems:


  1. 数组 answerYN 未(部分)初始化,其内容(也部分)不确定。这意味着 answerYN [1] 可能不是所需的字符串终止符。

  1. The array answerYN is (partially) uninitialized, its contents is (also partially) indeterminate. That means answerYN[1] is likely not the string terminator as needed.

alowwed_answerYN [0] 是单个 char ,而不是指向字符串的指针。

alowwed_answerYN[0] is a single char not a pointer to a string. This should have given you a warning about invalid conversions or similar.

如果您只是想比较字符,请使用正常相等性比较 == ,例如 answerYN [0] == alowwed_answerYN [0]

If you just want to compare characters, use normal comparison for equality ==, as in answerYN[0] == alowwed_answerYN[0].

或者为什么不完全跳过 alowwed_answerYN 并像 answerYN [0]一样简单地使用显式字符文字== 'Y'。这甚至比对'Y''N'使用数组更为清楚。

Or why not skip alowwed_answerYN completely and plainly use the explicit character literal as in answerYN[0] == 'Y'. That's even clearer than using an array for the 'Y' and 'N'.

这篇关于数组和scanf函数协同工作的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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