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

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
You have to explain more clearly.
What do you expect to happen? Why?
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?
On line 10, you set perspective to "bag". This never changes, so the if statement on line 25 will always be true
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
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).
Thank you guys for your help,
I am a beginner in C++, so this really helped, thx ^_^
Topic archived. No new replies allowed.