A mechanical engineer confused if IF ELSE statement can do this

vipandeep

vipandeep

@vipandeep-n6kj1q Oct 12, 2024
Hi

i have confusion. i am writing a C program for a quiz. i wanna know if we can give the user 2 tries to enter the answer. here is the simple program. please have a look.

#include <stdio.h>
int main()
{
	char ans, ans2;
	printf("What is the equivalent value of 0 Farenheit in Celcius?\na.) 0\nb.) -40\nc.) -17.78\n");
	scanf("%c",&ans);
	
	if (ans=='c')
	{
		printf("You are Smart!!!!!\n");
		
	}
	else
	{
		printf("You are Dumb!!!\n");
		printf("Give it another try\n");
		scanf("%c",&ans2);
		
		if (ans2=='c')
		{
			printf("Thank God!!!!......Finally you are correct\n");
		}
		else
		{
			printf("you are the Dumbest person on Earth\n");
		}}
	return 0;
}

Replies

Welcome, guest

Join CrazyEngineers to reply, ask questions, and participate in conversations.

CrazyEngineers powered by Jatra Community Platform

  • HirenBarbhaya

    HirenBarbhaya

    @hirenbarbhaya-04r651 Dec 6, 2010

    I am little confused about the question itself...

    If you wanna give second try then what you have written is correct... Seems fine to me... nothing wrong in it..
  • Manish Goyal

    Manish Goyal

    @manish-r2Hoep Dec 6, 2010

    very nice question vipan. Just add this function "flushall()" after else .

    Here is the reason when compiler encounters first scanf("%c",&ans);
    you will press say 'a' and then press enter ,compiler will consider your input as "a\n" ,thus here second scanf will take "\n" as its input and hence it will not wait for second input, if you put answer wrong ,so in order to ensure fine working of program ,you have to clear your input buffer and for that use flushall().
  • vipandeep

    vipandeep

    @vipandeep-n6kj1q Dec 7, 2010

    Thanks for the answers.

    I am using Xcode in mac. when i added flushall() it comes up with an error "warning: implicit declaration of function 'flushall'
    I dont trust Xcode because it shows same warning for system("PAUSE").
    any idea?
  • Leo

    Leo

    @leo-ZJQlmh Dec 7, 2010

    Hi Vipin try using fflush(stdin) or you can create your own flush function like this,

    void flush()
    {
    char *str;
    str=(stdin);
    return;
    }

    And system("PAUSE") is not error, pause is not system command for mac it is system command for windows. Xcode is perfectly fine standard compiler, you need little practice to differentiate between Linux, UNIX and Windows system commands, thats it nothing else.
  • vipandeep

    vipandeep

    @vipandeep-n6kj1q Dec 8, 2010

    Thanks Leo.... fflush(stdin) works well 😀