Noob need help

l just want to know how "GetYN" function is working like in "GetYN" function i declare that the "ch" does not equal to "Y and N" but when i am calling "GetYN" function l am declaring "GetYN()" equal to "Y".

l know l sound confusing but l need help.

any type of help would be appreciated.

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
  #include<iostream>
using namespace std;


int GetYN()
{
	char ch;
	do{
		cin>>ch;
		ch=tolower(ch);
		
	}while(ch !='y' && ch != 'n');
	return ch;
}
int Sum()
{
	int a,b;
	cout<<"Enter two numbers\n";
	cin>>a>>b;
	cout<<endl; 
	int sum=a+b;
	
	return sum;
	
}
int main()
{
do{
	cout<<Sum();
	cout<<"\nDo you want to continue Y/N\n";
	
}	while(GetYN()=='y');
}
but when i am calling "GetYN" function l am declaring "GetYN()" equal to "Y".

No you are comparing the return value from GetYN() (the character 'y' or 'n') to the value 'y'. In C++ there is a difference between the comparison operator== and the assignment operator=.

Hello Daim,

Welcome to the forum and thank you for using code tags.

In the function "GetYN" the do while continues until you press either 'y' or 'n' to cause the while loop to fail causing the the return value. You have the return value as an "int", but it would be better as a "char" since that is what "ch" is defined as.

In main the while condition is comparing the return value of the function to 'y'. Although it does work you are comparing an "int" to a constant "char". It would be nicer if they matched type of the variables.

As a note in the "Sum" function you could eliminate line 21 and have line 23 say return a + b; just as easily.

If I misunderstood your question let me know.

Hope that helps,

Andy
Topic archived. No new replies allowed.