I have a for loop in which values are entered for two different arrays, using two cout statements.
I need a way to end the loop and continue with the rest of the function after the value "-1" is entered into the first array. -1 is a signal that all data has been read.
I tried to use if and then break, but that didn't work. What other ways are there to end the loop? thanks so much for any help!
constint size = 100;
int id[size], I;
double balance[size];
for (I=0; I<size; I++)
{
cout << "Enter the customer's ID number: ";
cin >> id[I];
while (id[I]<1000||id[I]>9999)
{ cout << "You have entered an invalid ID. Please reenter: ";
cin >> id[I];
}
cout << "Enter the customer's balance: ";
cin >> balance [I];
while (balance[I]>10000)
{ cout << "You have entered an incorrect balance. Please reenter: ";
cin >> balance[I];
}
}
I would like to insert some sort of statement immediately after the first cout statement that would end the loop when id[I] == -1. I don't want it to go on to the while statements or the next cout one.
#include <iostream>
#include <sstream>
#include <string>
usingnamespace std;
// Handy little function to convert string to number
template <typename T>
bool string_to_number( const string& s, T& result )
{
// Try to transform that line into the result
stringstream ss( s );
ss >> result;
// Indicate if it succeeded or failed
returnbool( ss );
}
int main()
{
constint max_num_items = 100;
int id [ max_num_items ];
double balance[ max_num_items ];
int num_items;
string s;
cout << "Please enter the following requested information.\n""Press ENTER without typing anything else to finish.\n\n";
for (num_items = 0; num_items < max_num_items; num_items++)
{
cout << "Enter the customer's ID number: ";
while (true)
{
// Users expect to have to press ENTER after each input, so read the whole line
getline( ins, s );
if (s.empty()) break;
if (string_to_number( s, id[num_items] ) && (id[num_items] >= 1000) && (id[num_items] <= 9999)) break;
cout << "You have entered an invalid ID. Please try again: ";
}
if (s.empty()) break;
cout << "Enter the customer's balance: ";
while (true)
{
getline( ins, s );
if (s.empty()) break;
if (string_to_number( s, balance[num_items] ) && (balance[num_items] <= 9999)) break;
cout << "You have entered an incorrect balance. Please try again: ";
}
if (s.empty()) break;
}
cout << "Thank you.\n""You have entered " << num_items << " items.\n\n""Now to do some amazing math with them.\n\n";
...
return 0;
}