Continues no matter what I enter

Hello, in a calculator program I remade this morning, I had a problem. Here is 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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>
using namespace std;

int main()
{





    int a;
    char b;
    int c;
    char d;
    while (char d = 'y')
    {
    cin >> a;
    cin >> b;
    cin >> c;






    if (b == '-')
    {
        cout << a - c << endl;
    }

    if (b == '+')
    {
        cout << a + c << endl;
    }

    if (b == '*')
    {
        cout << a * c << endl;
    }

    if (b == '/')
    {
        cout << a * c << endl;
    }
    cout << "Would you like to continue?" << endl;
    cout << "y/n" << endl;
    cin >> d;
    }
    return 0;
}

for some reason, whether hit y or n doesn't matter, it will continue no matter what. CAn you please explain how to fix that?
line 15 while (char d = 'y') should be while (char d == 'y')
When I did that it gives me error:
expected primary expression before char
line 15 while (char d == 'y') should be while (d == 'y')
Now it compiles fine, but when I run it, the console just opens and says "press any key to continue" and I press it, and it closes
try to initialize (aka d='y';) BEFORE you enter while loop :)

Can be done on line 14 of original code as follows:
char d='y';

EDIT:
Reason being after you create variable without "real" assignment it can be nearly anything.
Last edited on
@eraggo
Thank you that worked, though, are you saying, like, because d didn't equal y until AFTER the loop starts, so it just skipped the loop?
Your variable can contain anything random if you won't assign something to it... another way (of course) would leave original declaration of variable and use do..while loop instead of while-loop.
In that case check for continuing is made after "real" do-block is executed :)

EDIT (again):
Test as follows :P
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
using namespace std;

int main()
{
int a;
char b;
int c;
char d;

do
{
	cin >> a;
	cin >> b;
	cin >> c;

	if (b == '-')
	{
	cout << a - c << endl;
	}

	if (b == '+')
	{
	cout << a + c << endl;
	}

	if (b == '*')
	{
	cout << a * c << endl;
	}

	if (b == '/')
	{
	cout << a * c << endl; // FIXME! (maybe you want to divide?)
	}

	cout << "Would you like to continue?" << endl;
	cout << "y/n" << endl;
	cin >> d;
} while (d=='y');

return 0;
}
Last edited on
Is there a way to do the same thing as
system("cls") without using that code?I want to make the actual program look neater
Topic archived. No new replies allowed.