I wrote a simple program which purpose is to find the greatest common divisor of two numbers, granted by the user (Euclidean algorithm).
#include <iostream>
using namespace std;
int main()
{
int a,b;
cin >> a;
cin >> b;
while (a!=b)
{
if (a>b)
{
a=a-b;
}
if (b>a)
{
b=b-a;
}
}
cout << a;
}
The code above is perfectly fine and works, but the problem I'm trying to deal with is that my teacher requires me to use a single line of cin
, like this:
#include <iostream>
using namespace std;
int main()
{
int a,b;
cin >> a,b;
while (a!=b)
{
if (a>b)
{
a=a-b;
}
if (b>a)
{
b=b-a;
}
}
cout << a;
}
And it absolutely does NOT work! The only difference is in the way the user is supposed to enter the data:
cin >> a,b;
instead of
cin >> a;
cin >> b;
Yet when I change that, the program is stuck in the while
loop.
According to what I tried many times, the user should be able to specify multiple arguments by hitting the space bar between the numbers (for example "10 8") but it somehow breaks the algorithm.
It just doesn't make sense to me. Why does that happen?