Condition seems to be ineffective

I'm attempting a simple little "Guess the number" game, but no matter which number you input, you always win. Here's the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main ()
{
  string str;
  int y = 0;

  cout << "Let's play \"Guess the number\". The number is between 0 and 10.\n";
  do
  {
       getline (cin, str);
       stringstream (str) >> y;
       cout << "You entered " << y;
       if (y = 4)
       {
            cout << ". Correct. Well done!\n";
       } else {
            cout << ". Incorrect. Try again.\n";
       }
  } while (y != 4);
  system ("PAUSE");
  return 0;
}


It seems as if the condition in the loop is ignored. Can someone please tell me what I'm doing wrong?
if (y = 4)
line 17 needs to be

if (y == 4)

also use of system() is bad practise, it's a huge security flaw waiting to happen. you can do this instead:

getline(cin, str);

then the user only needs to hit the enter key to exit.
Last edited on
= is assignment operator
== is conditional operator
Ah, thanks.
lolol 3 replies all in the same minute....
if (y = 4)

now think about it. :-)
i suggest you add number randomization and tell the user if his input is higher or lower than the target number..
Topic archived. No new replies allowed.