Can't stop the program from closing, tried what I know with no avail :(

I was taking an exam earlier, It was the simplest question ever. Run this program using the input 3/7 and post the output. I had tried everything to stop the program from closing to quickly. Although the exam is over (had to guess the output) I would still like to know what i was doing wrong and how to stop this problem in the future. (I have removed my code for system "pause" since it wasn't working)

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
#include <iostream>
using namespace std;
class Rational {
     friend ostream& operator<< (ostream&, const Rational&);
     friend istream& operator>> (istream& in, Rational&);
public:
   Rational (int=0, int=1);
private:
     int num, den;
};
int main(){
     Rational x(22,9), y;
     cin>>y;
     cout << "x =  " << x << " and y =  " << y << endl;
     return 0;
}
Rational::Rational (int n, int d){
     num=n;den=d;
}

ostream& operator<<(ostream& out, const Rational& r){
     return out << r.num << '/' << r.den;
}
istream& operator >> (istream& in, Rational& r){
     char ch;
     cout << "Input a rational in the form of a/b: " << endl;
     if (in >> r.num && in >> ch && ch == '/' && in >> r.den)
     return in;
} 

int max (int x, int y){
   if (x > y) return x;
   else return y;

}

Last edited on
I usualy do this at the end:

1
2
3
std::cout << "press Enter to close" << std::endl;
std::cin.ignore(99, '\n');
return 0;


howerver if you used cin somewhere, as you did, then also add cin.get() first. so it catches the last 'enter' you did and don't skip through the end.

Never use system "pause". That's bad practice.
Last edited on
If you run from a command prompt or terminal you won't have this issue.
Yep and some compilers you can do ctrl+F5
IDEs*
IDEs*


right :p
Topic archived. No new replies allowed.