-1

I'm trying to make the 20 questions game using c. The following is the code excerpt of one of the functions.

int question_input(void)
{
    char q[100];
    int i=0;
    printf("Enter the question or say if you want to guess\n");
    scanf("%[^\n]",q);
    i=check_if_guess(q);
    if(i==0)
    {
        printf("Say yes or no\n");
        scanf("%s",q);
    }
    return i;
}

I get a general protection fault when I execute and on debugging, I found that the problem is with the

scanf("%[^\n]",q)

statement.

If the same statement is changed to "%s", then, I get no segmentation fault. Functions like gets (general protection fault) and fgets(doesn't ask for input at all) also fail to take inputs.

The thing which is more curious is that when I execute these statements in a seperate file, without the rest of the code, they execute properly.

Even if I try "%99[^\r\n]", it shows the same.

Please help

1 Answers1

0

Well, I found an answer to my question by myself. One of my previous functions in my code had

scanf("%d",&n)

It is a known fact that after we enter our input we press the enter key. This is taken as a '\n' by the compiler and is stored in the buffer. My next scanf statement( the one which I got error in)(scanf("%[^\n]",q) straight away took the '\n' from the buffer. Hence it could not take any input, since \n terminates input. The compiler I use is turbo C++. In some cases of empty strings, it reports an error. Hence I got the error message. To solve this problem, I had to use

getchar()

statement before the scanf("%[^\n]",q) statement, so that the '\n' is removed from the buffer and taken as an input for the getchar statement.