Hristo Kamenov
Hristo Kamenov

Reputation: 21

The code "should" work, but the program stops working

I'm a beginner with a few hours of expirience and I'm trying to make a really simple program to get familiar withe IF command. I came up with this code:

#include<stdio.h>

int main()
{
    char ans;
    char n;
    char y;
    printf("Do you want to exit?\n");
    scanf("%c\n",ans);
    if (ans == y)
    {
        printf("As you wish!\n");
        return 0;
    }
    else (ans == n);
    {
        printf("You'll exit anyways!\n");
        return 0;
    }
}

I think it should work, but after I type something the program stops workig! Thanks in advance!

Upvotes: 0

Views: 102

Answers (3)

NPE
NPE

Reputation: 500177

The

if (ans == y)

should read

if (ans == 'y')

The former compares ans to the value of the uninitialized variable y, whereas the latter checks whether ans contains the character 'y'.

The same goes for 'n'.

The y and n variables are unnecessary and can be removed.

Also, the following line is incorrect:

else (ans == n);

It should read

else if (ans == 'n')

(I've added the if and have removed the semicolon.)

Finally, the scanf() should read:

scanf("%c",&ans);

Upvotes: 9

user123
user123

Reputation: 9071

else (ans == n);

This doesn't give expected results. Remove the ; and the condition. else may only take a body of code. It does not handle conditions. If you want conditions, use else if:

else if (ans == 'n')

More errors:

if (ans == y)

y in here refers to the variable, which is declared but has no value. Surely you want to refer to the character 'y':

if (ans == 'y')

Also, scanf expects a pointer, so instead of ans, use &ans. It needs to write to the memory address of the value. It doesn't care about the value. You'll learn about pointers eventually. (Assuming you haven't gone over them in your few hours of experience)

Upvotes: 3

md5
md5

Reputation: 23699

There are three main errors.

  • You should pass pointers to the scanf function, so you have to add an ampersand before ans (&ans).

  • There is a trailing ; at the end of the else statement.

  • y refers to a variable (which does not exist), whereas you want to compare ans against the character 'y'.

Upvotes: 2

Related Questions