I would like to have the user enter ctrl-z to end the program...can someone tell me how to insert this into the following program?

``````//Program to calculate greatest common denominator of two integers

#include <iostream>

using namespace std;

int calcGCD(int, int);

int main()
{
int a, b, res;

cout <<"This program will determine the greatest common divisor of "
<< "two positive integers. ";
cout <<endl;
cin >> a;
cin >> b;
cout <<endl;

while ( a > 0 && b > 0 )
{
res = calcGCD ( a, b );

cout << "Greatest common divisior (GCD) of "<< a <<" and "<<b<<" is "<<res;
cout <<endl;
cout <<endl;
cout << "Please input your first positive number: (or ctrl-z to end program) ";
cin >> a;
cin >> b;
}

system ("pause");
return 0;
}
int calcGCD (int a, int b)
{
int c;

if ( a < b )
swap (a, b);

c = a % b;
if ( c == 0 )
return b;
calcGCD ( b, c );
}
/*

if ( b > a )
swap (a, b);
while ( b != 0 )
{
temp = b;
b = a - b;
a = temp;
if ( b > a )
swap (a, b);
}
return GCD;

system ("pause");
return 0;

}*/``````

When `cin` encounters Ctrl-Z, `cin.eof()` will return true. So e.g.

``````if(cin.eof())
{
cout << "bye ...";
return 0;
}``````

thanks much, worked like a charm

Why not just hit Ctrl-C. It'll stop the program too. :icon_wink:

You need to test the return from `cin` and look for EOF

You need to test the return from `cin` and look for EOF

Am I missing something (big time), or isn't that just what

``if(cin.eof())``

does?

Yes it does. But when I opened the thread at around 3:12 the other posts weren't there. Then I got called away and finished my post at 3:37.

Yes it does. But when I opened the thread at around 3:12 the other posts weren't there. Then I got called away and finished my post at 3:37.

LOL, a nice mix-up.

here is a code to read an array of characters until user press CTRL+C

``````void read_ctrl_z(char *x){
int i = 0;
while (true) {
x[i++] = getch();
if(x[i-1] == 26) {
x[i-1] = '\0';
cout<<endl;
break;
}else{
cout<<x[i-1];
}
}
}``````
commented: Why 11 years late? -4
commented: It could still be useful to someone. +34
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.