#include<iostream.h>
#include<process.h>
int sum(int &x,int &y)
{
return (x+y);
}
int main()
{
int a,b;
do
{
cout<<"\nEnter 2 Values : ";
cin>>a>>b;
cout<<"\nThe Sum is : "<<sum(a,b);
cout<<"\nDo You Want to continue ?(y/n)..."
cin>>ch;
}while((ch=='y')||(ch=='Y'));
if((ch!='y')||(ch!='Y'))
{
cout<<"\nThankyou for using the Program !!!"; //This output is not clearly given to the user when he exits the program (WHY...?)?
exit(1); //How can we rectify this problem ?
}
return 0;
}
#include<iostream.h>
#include<process.h>
int sum(int &x,int &y)
{
return (x+y);
}
int main()
{
int a,b;
do
{
cout<<"\nEnter 2 Values : ";
cin>>a>>b;
cout<<"\nThe Sum is : "<<sum(a,b);
cout<<"\nDo You Want to continue ?(y/n)..."
cin>>ch;
}while((ch=='y')||(ch=='Y'));
if((ch!='y')||(ch!='Y'))
{
cout<<"\nThankyou for using the Program !!!";
for(int i=0;i<500;i++)
{
//Like this ----->NULL LOOP
}
exit(1);
}
return 0;
}
Nothing. (1) compiler is likel to optimize away that loop
(2) consider this:
1 2 3
cout<<"\nThankyou for using the Program !!!"; //Nothing displayed yet, buffer is not flushed
//<useless loop>
exit(1); //Now, after exit call, during destruction of static objects, cout buffer is flushed and text is actually displayed.
You can actually manually flush input buffer but it is not a good idea. It just masks the problem instead of solving it (not to mention that busy waiting is worst thing you can do). Correct way is to configure your IDE properly. (for visual studio run with ctrl+F5). If you are running outside IDE, run as it is intended: through comand line.
To force a stream to write out buffered output immediately, flush it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
#include <cstdlib>
#include <thread>
#include <chrono>
int main()
{
// flush: http://en.cppreference.com/w/cpp/io/manip/flush
// flush std::cout before the spawned process writes to stdout
std::cout << "you are: " << std::flush ;
std::system( "whoami" ) ;
// flush std::cout before entering a wait state
std::cout << "thank you for using the program!\n" << std::flush ;
std::this_thread::sleep_for( std::chrono::seconds(2) ) ;
}