Thread: I don't understand

  1. #1
    Registered User
    Join Date
    Oct 2011
    Posts
    5

    I don't understand

    hi.. this is my code:

    Code:
     #include <iostream>
    using namespace std;
    int main()
    {
        
        float a,b;
        char ex[]="n";
        do {
        cout<<"a=: " ; cin>>a;
        cout<<"b=: " ; cin>>b;
        cout<<"a/b= "<<a/b<<endl<<endl;
        cout<<"Stop? (y/n): "; cin>>ex;
        if (ex=="Y"||"y"){
        return 0; 
        }
        }while((ex!="y")||(ex!="Y"));
        
    }



    I don't know what's wrong with this program..even I press n or N it exit..I want to repeat if I press n or N.
    can someone help me?

  2. #2
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by AndreyS10 View Post
    ..even I press n or N it exit..I want to repeat if I press n or N.
    can someone help me?
    Because this:

    Code:
     if (ex=="Y"||"y"){
    Means:

    if ex=="Y" is true
    OR
    if "y" is true


    "y" is not zero, so the second condition is always true.

    Also, " and ' are different. "Y" indicates a string literal, and ex is a c-string, but you cannot compare one such string to another with ==. You can, however, compare single char values, but a char value is single quoted.

    So perhaps you want something more like:

    Code:
     char ex='n';  // single char instead of a c-string
    if (ex == 'Y' || ex == 'y'){   // single quotes around char values
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  3. #3
    Registered User
    Join Date
    Oct 2011
    Posts
    5
    thank you..I works..
    I'm new to programming so I still learn.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. please help me understand this
    By litzkrieg in forum C Programming
    Replies: 8
    Last Post: 02-16-2011, 01:44 PM
  2. I don't understand this
    By Dontgiveup in forum C++ Programming
    Replies: 14
    Last Post: 03-28-2009, 07:04 PM
  3. i cant understand this!!
    By thongsai in forum C++ Programming
    Replies: 4
    Last Post: 04-18-2003, 09:09 PM
  4. Help me understand this
    By Shadow12345 in forum C++ Programming
    Replies: 8
    Last Post: 05-23-2002, 07:58 AM
  5. anyone understand this?
    By Da Beav in forum C Programming
    Replies: 6
    Last Post: 09-06-2001, 12:39 PM