!!! HELP AN IF FUNCTION PROGRAM (cmd project)

Sep 20, 2017 at 9:10pm
Hello there people of cplusplus.com ;3
I am having quite a bit of trouble with my program here, (ran on if functions) because im a n0b.

when I try to write down something, both of the if statements pop up, (the couts) instead of one, how can I fix this?

anyway 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
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

int main()
{

	int age = 12;
	string perspective = "bag";

	cout << "guess my age" << endl;
	cout << "  " << endl;
	cout << "  " << endl;

	cin >> age;

	if ( age == 12 ) {
		cout << "my age is 12" << endl;
	}

	else
		cout << "my age is not 12" << endl;

	if (perspective == "bag") {
		cout << "you guessed goodness, congratz.." << endl;
	}

	system("PAUSE");
    return 0;
}
Last edited on Sep 20, 2017 at 9:29pm
Sep 20, 2017 at 9:45pm
You have to explain more clearly.
What do you expect to happen? Why?
Sep 21, 2017 at 8:05am
When I type in 12, it should say "my age is 12" and that is it. HOWEVER, it also says the cout for the magic word which is "you guessed goodness, congratz..", I only want "my age is 12" how can I fix this little bug?
Sep 21, 2017 at 8:12am
On line 10, you set perspective to "bag". This never changes, so the if statement on line 25 will always be true
Sep 21, 2017 at 8:26am
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
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

int main()
{

	int age = 12;
	string item= "bag";//you must use meaningful variables

	cout << "guess my age" << endl;
	cout << "  " << endl;
	cout << "  " << endl;

	cin >> age;

	if ( age == 12 ) {
		//cout << "my age is 12" << endl;   -> Dont hard code the 12, use your variables
cout<<"My age is "<<age<<endl;
	}

	else
		while(age != 12)
{
cin>>age;
}
string answer;
cout<<"Guess the item: ";
cin>>answer;

	if (answer == item) {
		cout << "you guessed goodness, congratz.." << endl;
	}
else
cout<<"Too bad for you!"<<endl;

	system("PAUSE");
    return 0;
}
Last edited on Sep 21, 2017 at 8:27am
Sep 21, 2017 at 8:39am
I only want "my age is 12" how can I fix this little bug?

Remove lines 25--27?

The first if else covers only lines 18--23. It executes either line 19 or line 23, depending on what the user types.

The second if (25--27) is unrelated.


Do notice that you wrote braces around line 19 and around line 26, but not around line 23. You could have multiple statements within braces. You could have braces after the else, i.e. around line 23 (or even enclosing lines 23-27, if that is what you want).
Sep 21, 2017 at 9:52am
Thank you guys for your help,
I am a beginner in C++, so this really helped, thx ^_^
Topic archived. No new replies allowed.