As I wrote in one of my post - why you should use cin.get() when you test a program (apply to IDE that wont wait as you test a code and as soon as the code finished the window closes, leaving you without a glance on the result =p).
Let's look at this example:
#include <iostream>
using namespace std;
main()
{
for(int x=0;x<20;x++)
{
cout<<x<<endl;
}
cin.get();
}
using namespace std;
main()
{
for(int x=0;x<20;x++)
{
cout<<x<<endl;
}
cin.get();
}
But sometimes, cin.get() might refuses to work, as in this example here:-
#include <iostream.h>
main()
{
int hours, minutes, seconds;
cout <<"Input hours: ";
cin >> hours;
cout <<"Input minutes: ";
cin >> minutes;
seconds=hours*3600+minutes*60;
cout << "Time in seconds : "<<seconds<<endl;
cin.get();
return 0;
}
main()
{
int hours, minutes, seconds;
cout <<"Input hours: ";
cin >> hours;
cout <<"Input minutes: ";
cin >> minutes;
seconds=hours*3600+minutes*60;
cout << "Time in seconds : "<<seconds<<endl;
cin.get();
return 0;
}
The window closes taking all the data with it, and you not even get a chance to see the result.
What happen here actually?
Why cin.get() works in the first example but not in the second?
In the second example, after the program read the value using cin, a \n is left in the buffer. Thus the cin.get() that you meant for pausing consumes that \n.
What you can do??
You may use two cin.get(). Which the first call to cin.get() is used to consumes that \n left in the buffer and the second cin.get() to pause your windows from closing.
Or, you may flush the \n from the buffer by using cin.ignore()
#include <iostream.h>
main()
{
int hours, minutes, seconds;
cout <<"Input hours: ";
cin >> hours;
cout <<"Input minutes: ";
cin >> minutes;
seconds=hours*3600+minutes*60;
cout << "Time in seconds : "<<seconds<<endl;
cin.ignore();
cin.get();
return 0;
}
main()
{
int hours, minutes, seconds;
cout <<"Input hours: ";
cin >> hours;
cout <<"Input minutes: ";
cin >> minutes;
seconds=hours*3600+minutes*60;
cout << "Time in seconds : "<<seconds<<endl;
cin.ignore();
cin.get();
return 0;
}
No comments:
Post a Comment