Incorrect Output

I am doing an assignment for a class in which the user must input a grade for their last test and the program will return with whether they passed or failed that test (60 or over being passing). The program must have three functions besides main(), one to prompt the user for their grade, one to display that they failed, and one to display that they passed. My issue is that the program always responds with "You failed the test." regardless of what grade I input. Please help! Thanks!

#include <iostream>
using namespace std;

int prompt()
{
int grade;
cout << "What was your grade on the last test? ";
cin >> grade;
return 0; // I have also tried "return grade;" here
}

int fail()
{
cout << "You failed the test.\n";
return 0;
}

int pass()
{
cout << "You passed the test.\n";
return 0;
}

int main()
{
int grade;
prompt();
if (grade < 60)
fail();
else
pass();
return 0;
}
Op’s Code, formatted
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 prompt()
{
   int grade;
   cout << "What was your grade on the last test? ";
   cin >> grade;
   return 0; // I have also tried "return grade;" here
}

int fail()
{
   cout << "You failed the test.\n";
   return 0;
}

int pass()
{
   cout << "You passed the test.\n";
   return 0;
}

int main()
{
   int grade;
   prompt();
   if (grade < 60)
      fail();
   else
      pass();
   return 0;
}
Grade doesn’t exist after the prompt function on line 28

Edit: the int grade in main() is not the same int grade in prompt(), instead maybe change prompt() to return grade and initialize the int grade in main() to prompt():

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

int prompt()
{
   int grade;
   cout << "What was your grade on the last test? ";
   cin >> grade;
   return grade; // I have also tried "return grade;" here
}

int fail()
{
   cout << "You failed the test.\n";
   return 0;
}

int pass()
{
   cout << "You passed the test.\n";
   return 0;
}

int main()
{
   int grade = prompt();
   if (grade < 60)
      fail();
   else
      pass();
   return 0;
}


Or you could pass grade to prompt and return it.

1
2
3
4
5
6
7
8
9
10
11
12
int prompt(int grade)
{
   cout << "What was your grade on the last test? ";
   cin >> grade;
   return grade; // I have also tried "return grade;" here
}
...
int main(){
   int grade;
   prompt(grade);
   ...
}
Last edited on
return 0; // I have also tried "return grade;" here

Well, do that again...but then use it with something like:

int grade = prompt();
It worked! I am still a beginner at C++ so thank you for the help!
Registered users can post here. Sign in or register to post.