Thread: Error In a While Loop

  1. #1
    Registered User
    Join Date
    Dec 2011
    Posts
    34

    Error In a While Loop

    I am doing some Programming exercises from the book I am learning C++ from, C++ Primer Plus. I was doing one of the examples and I have ran into a problem with some of my code.

    Code:
    #include <iostream>
    
    
    using namespace std;
    
    
    int main()
    {
        cout << "Please enter one of the following choices: \n";
        cout << "c) carnivore    p)pianist\nt)tree          g)game\n";
        char in;
        cin >> in;
        while( in != 'c' || 'p' || 't' || 'g'){
            cout<<"Please enter a c, p, t, or g: ";
            cin >> in;
        }
        cout<< endl;
        switch(in){
            case 'c':
                cout<<"A lion is a carnivore.";
                break;
            case 'p':
                cout<<"A pianist is a piano player";
                break;
            case 't':
                cout<<"A maple is a tree.";
                break;
            case 'g':
                cout<<"Mine sweeper is a game.";
                break;
        }
        return 0;
    }
    I believe everything is working as I want except for the while loop
    Code:
    while( in != 'c' || 'p' || 't' || 'g'){
            cout<<"Please enter a c, p, t, or g: ";
            cin >> in;
        }
    I have tried putting the stuff on the right side of the != in parenthesis, changing it to a == and putting a ! infront of the entire thing.

    Does anyone have any suggestions on what might be wrong with my code? I am not able to see what all is wrong.

  2. #2
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    This is what you mean:
    Code:
    while( in != 'c' && in != 'p' && in != 't' && in != 'g')
    The cost of software maintenance increases with the square of the programmer's creativity. - Robert D. Bliss

  3. #3
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    You must have both sides of the equation for each AND or OR.
    Code:
    while( a == b || b == c)
    Jim

  4. #4
    Registered User
    Join Date
    Dec 2011
    Posts
    34
    Oh wow I feel like I should of known that. Thank you to both of you for the help.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. error (do-while)loop
    By prehisto in forum C Programming
    Replies: 8
    Last Post: 10-30-2011, 09:06 AM
  2. Do While Loop Error
    By mintsmike in forum C Programming
    Replies: 4
    Last Post: 03-24-2009, 02:45 PM
  3. error with my for loop?
    By rs07 in forum C Programming
    Replies: 1
    Last Post: 07-25-2008, 07:12 PM
  4. Loop seg error
    By Zishaan in forum Game Programming
    Replies: 2
    Last Post: 03-28-2007, 01:27 PM
  5. error in a for loop
    By saahmed in forum C Programming
    Replies: 11
    Last Post: 03-10-2006, 12:44 AM