Sign in to follow this  
Mahoutsukai

Newbie code problem!!

Recommended Posts

Why do I get an infinit loop with this code?
#include <iostream>
#include <iomanip>

using namespace std;

int main ()
{
  int sells;
  double salary;
  
  cout << "Imput sells (-1 to end): ";
  cin >> sells;
  
  while ( sells != -1 ){
     salary = 200 + static_cast< double >( sells ) * 0.09;
     
     cout << setiosflags ( ios::fixed | ios::showpoint )
          << setprecision( 2 );
     cout << "salary is: " << salary << endl;
     
     cout << "Imput sells (-1 to end): ";
     cin >> sells;
  }
  
  return 0;
}

[Edited by - Mahoutsukai on September 21, 2004 1:50:32 AM]

Share this post


Link to post
Share on other sites
I don't know enough about coding to reply, so not sure why I am replying, but...


it is only infinite until you type -1

you should also double sells instead of int sells if salary is double. Otherwise if you type a decimal number it goes on and on and on...

Also, not sure why it keeps going if you type a letter. You need some error handling.

Share this post


Link to post
Share on other sites
Does this work any better?


#include <iostream>
#include <iomanip>

using namespace std;

int main ()
{
int sells;
double salary;

cout << "Imput sells (-1 to end): ";
char sellsTemp[10];
cin >> sellsTemp;
sells = atoi(sellsTemp);

while ( sells != -1 ){

salary = 200 + static_cast< double >( sells ) * 0.09;

cout << setiosflags ( ios::fixed | ios::showpoint )
<< setprecision( 2 );
cout << "salary is: " << salary << endl;

cout << "Imput sells (-1 to end): ";

//sellsTemp[10];
cin >> sellsTemp;
sells = atoi(sellsTemp);

}

return 0;
}




Your code worked fine, until I entered a character. Then it went into an infinite loop. Typing -1 exited fine. Perhaps the platform you are developing interprets -1 as a character... although Im only just getting to grips with C++ myself so I wouldn't take my word for it.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this