Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
129 views
in Technique[技术] by (71.8m points)

c - Problems with array and scanf function working together

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.

(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.)

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.

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("
Enter your number from %i to %i, "
            "and I will try to guess!: ",Llimit,Hlimit);
    
    while(scanf("%i",&numberTOguess) )
    {
        int check=rand()%Hlimit;
        printf("
your number is - %i Y/N?",check);
        scanf("%c",&answerYN[0]);
        printf("answer is %c
", 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("
your 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("
I 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;
    
}

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.

Look at the code:

#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("
Enter your number from %i to %i, "
            "and I will try to guess!: ",Llimit,Hlimit);
    
    while(scanf("%i",&numberTOguess) )
    {
        int check=rand()%Hlimit;
        printf("
your number is - %i Y/N?",check);
        scanf("%c",&answerYN);
        
        switch(answerYN)
        {
            case 'Y':
                printf("I did it!");
                break;
            case 'N':
                printf("
Ok, 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("
END!");
    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

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.

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.

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.

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.

answered Mar 5 '12 at 7:05
Jonathan Leffler

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

With e.g.

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

you have two major problems:

  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.

  2. 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.

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

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'.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...