Results 1 to 2 of 2

Thread: While Loop Problem!!pls Help

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Jul 2002
    Posts
    75

    While Loop Problem!!pls Help

    hello friends...
    In the C++ program below..there is something wrong in the While Loop. logic.What i want is that when we type
    the letters --> y,Y,n or N then the program should exit.,else
    it should not exit and then print as in the cout.
    But the code is not working for me.it doesnt not exits even if when we enter --> y,Y,n or N.
    Plss check the while loop and reply me with modifications

    Thanx in advance
    Prasad

    Here is the code below:--

    #include<iostream.h>
    main()
    {
    char answer;
    while ( (answer != 'y') || (answer != 'Y') || (answer != 'n') || (answer != 'N') ) //error checking for answer
    {

    cout << "Illegal character. Please enter again." ;
    cin >> answer ;

    } }

  2. #2
    PowerPoster sunburnt's Avatar
    Join Date
    Feb 2001
    Location
    Boulder, Colorado
    Posts
    1,403
    Here is one way to do it...
    Code:
    #include <iostream.h> 
    
    main() 
    { 
    	char answer; 
    	do
    	{
    		cout << "Please enter a valid answer: ";
    		cin >> answer;
    
    	}while(answer != 'y' && answer != 'Y' && answer != 'n' && answer != 'N');
    }
    And here is another, more closely resembling yours.
    Code:
    #include <iostream.h> 
    
    main() 
    { 
    	char answer; 
    	
    	cout << "Enter answer: "
    	cin >> answer;
    
    	while(answer != 'y' && answer != 'Y' && answer != 'n' && answer != 'N')
    	{
    		cout << "Invalid answer, try again: ";
    		cin >> answer;
    	};
    
    }
    The problem was this line:
    (answer != 'y') || (answer != 'Y') || (answer != 'n') || (answer != 'N')

    This can be rewritten (according to D'morgan's law) as:

    !(answer == 'y' && answer == 'Y' && answer == 'n' && answer == 'N')

    which you can see is the exact opposite of what you want :-D

    so either of these will work:
    (answer != 'y' && answer != 'Y' && answer != 'n' && answer != 'N')

    or

    !((answer == 'y') || (answer == 'Y') || (answer == 'n') || (answer == 'N'))

    Cheers.
    Every passing hour brings the Solar System forty-three thousand miles closer to Globular Cluster M13 in Hercules -- and still there are some misfits who insist that there is no such thing as progress.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width