Reputation:
My professor asks that we use the while function in c++ for a code we are writing. I keep returning the same error, so I wrote a simple simple code to understand the while loop. Still stuck at this part. It obviously isn't the end of my program, I just gets stuck at the while function. Any ideas?
#include <iostream>
#include <cstdlib>
using namespace std;
void response (){
cout<<" Continue loop function?\n";
cout <<"y - yes\nn - no\n";
char response='y';
cin>> response;
return;
}
int main (){
response ();
while (response=='y')
return 0;
}
Upvotes: 2
Views: 84
Reputation: 14313
There are several things wrong here. Your main function should probably look like this:
int main()
{
while (response() == 'y')
{ //must have either an empty body or a semicolon here,
//otherwise our return statement will become the loop body!
}
return 0;
}
Also, your response()
function should return the local variable response
so its value can be returned to main
. You can't use the response
variable outside of the response function because of scope.
What your (erroneous) main function currently does is call the response()
function and then try to compare your response function to the char literal 'y'
. However, this isn't comparing the value just returned from your function, it's comparing the memory address (pointer) of the function itself.
C++ allows you to have variables and functions with the same same, but it's usually a bad idea. You might want to give either your response()
function or the response
local variable a different name.
Upvotes: 2
Reputation: 1
You can't access the function local response
variable in main()
.
In this line
while (response=='y')
response
is interpreted as the address of the response()
function, compared to 'y'
which causes the error you see.
As others mentioned you should rather have something like this
char response (){
cout<<" Continue loop function?\n";
cout <<"y - yes\nn - no\n";
char resp='y';
cin >> resp;
return resp;
}
int main (){
while (response()=='y'); // << also note the semicolon here
return 0;
}
Upvotes: 2
Reputation: 29441
While is waiting for a boolean. In order to compare 'y' to response, you must change the return type from void to char :
char response (){
cout<<" Continue loop function?\n";
cout <<"y - yes\nn - no\n";
char response='y';
cin>> response;
return response;
}
Upvotes: 1