2 Replies - 191 Views - Last Post: 03 February 2018 - 03:48 PM Rate Topic: -----

#1 kianyt  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 17
  • Joined: 03-February 18

Help with basic code

Posted 03 February 2018 - 03:04 PM

Can anyone tell me why this doesn't work? no matter what number I enter it outputs "Congratulations you lost"
#include <iostream>
using namespace std;

int main()
{
int number;
 cout << "Please enter any number except 5" << endl;
    cin >> number;
 if (number = 5){
    cout << "Congratulations. You lost." << endl;
 }else{
    cout <<"You won." << endl;

 }

    return 0;
}



Is This A Good Question/Topic? 0
  • +

Replies To: Help with basic code

#2 sepp2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2603
  • View blog
  • Posts: 4,157
  • Joined: 21-June 11

Re: Help with basic code

Posted 03 February 2018 - 03:24 PM

= is the assignment operator in C++ (== is the equality operator). It sets the given variable (or other l-value) to the given value and then evaluates to that value. So if (number = 5) {...} is equivalent to number = 5; if (5) {...} and 5 as a condition is always true.
Was This Post Helpful? 4
  • +
  • -

#3 tony jay  Icon User is offline

  • D.I.C Head

Reputation: 18
  • View blog
  • Posts: 50
  • Joined: 31-January 18

Re: Help with basic code

Posted 03 February 2018 - 03:48 PM

We all make this mistake from time to time.
From now on the OP will quickly grock the error though...

Nice concise and accurate explanation BTW!

This post has been edited by ndc85430: 03 February 2018 - 10:45 PM
Reason for edit:: Removed quote of previous post. Please just press "Reply" in future.

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1