I just want it to run the program until its told not to, but once i hit the bottom I go into an infinite loop.
It seems that I am retaining the gcout value but I thought I eliminated it with str.clear?? I also tried str.erase to no avail
#include <cstdlib>
#include <iostream>
usingnamespace std;
int main(int argc, char** argv) {
//Declare all variables
int starting_balance, checks, deposits;
char ans;
do{
string str;
cout<<" Enter 4 digit account number #";
//Restrict valid input to 4 digits
//reference: http://msdn.microsoft.com/en-us/library/3w9exa29(v=vs.80).aspx
cin.get( &str[0],6 );
if (cin.gcount( )==4){
//prompt for input
cout<<" What is your starting balance this month?"<<endl;
cout<<" $";cin>>starting_balance;
cout<<" What is the total of checks written from this account?"<<endl;
cout<<" $";cin>>checks;
cout<<" What is the total deposits into this account?"<<endl;
cout<<" $";cin>>deposits;
//calculate new balance and output results
if ((starting_balance-checks+deposits)<0){
cout<<" Looks like your down on your luck"<<endl;
cout<<" Your balance is $"<<starting_balance-checks+deposits<<" but...."<<endl;
cout<<" We have to charge you $20 because you were overdrawn, so now your balance is $"<<starting_balance-checks+deposits-20<<endl;
cout<<" Dont worry...The sun will come out tomorrow, bet your bottom dollar...oops you dont have a bottom dollar"<<endl;
}elseif (starting_balance-checks+deposits==0){
cout<<" Well there you have it your balance is $0"<<endl;
cout<<" It's better than a stick in the eye I suppose"<<endl;
}else {
cout<<" Your new balance is $"<<starting_balance-checks+deposits<<endl;
cout<<" Dont spend it all in one place...unless its Walmart..they have everything!"<<endl;
}
}
//Error for input != 4
else{
cout<<"Invalid Entry"<<endl;
}
//Clear string gcount value reference: http://www.cplusplus.com/reference/string/string/clear/
//prompt for global loop
cout<<" Would you like to start again?"<<endl;
str.clear();
cout<<" ";cin>>ans;
}while(ans=='y'||ans=='Y');
//Exit the program
return 0;
Don't do this. &str[0] doesn't exist (bad pointer) because str is empty. You are giving a bad pointer to cin.get and telling it that it can write 6 characters there when it isn't safe to write any.
Since you have a string, use the string version of getline: