Jump to content

Check out our Community Blogs

Register and join over 40,000 other developers!

Recent Status Updates

View All Updates

- - - - -

boolean operator in If statement syntax

syntax bool

  • Please log in to reply
3 replies to this topic

#1 lithiummethoxide


    CC Newcomer

  • Just Joined
  • PipPip
  • 10 posts

Posted 22 February 2009 - 03:03 AM

I have a do-while loop in my program to check to make sure that a user's input is valid. (They have to enter 'y' or 'n'). If it isn't than the loop tells them it's wrong and to enter the letter again. But the loop doesn't work with the letter 'n'. It says it is an invalid input.

		ynCheck = 0;

		if (test != 'y' && 'n')
			printf("%c is an invalid input. Please enter a valid input.\n", test);
			printf("Would you like to enter another triangle? (y/n)\n");
			scanf("%c", &test);
			ynCheck = 1;

	}while (ynCheck == 0);

If anyone would like me to post the entire program so that this will compile sucessfully please ask.
  • 0

#2 Termana


    CC Devotee

  • Just Joined
  • PipPipPipPipPipPip
  • 971 posts

Posted 22 February 2009 - 03:14 AM

test will never equal y and n you need to use || instead of && also you may need to change the single quotation marks to double quotation marks but i'm not sure on that one.
Posted via CodeCall Mobile
  • 0

#3 WingedPanther73


    A spammer's worst nightmare

  • Moderator
  • 17757 posts
  • Location:Upstate, South Carolina
  • Programming Language:C, C++, PL/SQL, Delphi/Object Pascal, Pascal, Transact-SQL, Others
  • Learning:Java, C#, PHP, JavaScript, Lisp, Fortran, Haskell, Others

Posted 22 February 2009 - 04:00 AM

		if (test != 'y' && 'n')
The problem is with your if statement: This is how the compiler interprets it:

Compare the result of (test != 'y') to ('n') using &&
when you've inputted 'n', the results are:
(test != 'y') is true, 'n' is not 0 so interpretted as true, true && true is true.

I think what you meant was
		if (test != 'y' && test != 'n')

  • 0

Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

My MineCraft server site: http://banishedwings.enjin.com/

#4 lithiummethoxide


    CC Newcomer

  • Just Joined
  • PipPip
  • 10 posts

Posted 22 February 2009 - 01:06 PM

Yes! It works. Thank you so much guys. You have saved me hours of me getting my head around this.
  • 0

Also tagged with one or more of these keywords: syntax, bool

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download