Reputation: 19
We are supposed to create a program that accepts 15 telephone numbers. All numbers consist of 8 digits. Fixed lines start with 17 and mobile lines start with 39. Prog should cout the number of fixed and mobile lines. Also, prog should stop when the user enters a negative number.
Here is my code:
#include <iostream>
using namespace std;
void main ()
{
int n, c=1, cm=0, cf=0;
cout << "Enter a telephone number or enter a negative number to stop ";
while (c <= 15){
cin >> n;
if (n/1000000 == 39){
c++;
cm++;
}
else if (n/1000000 == 17){
c++;
cf++;
}
else cout << "Wrong telephone number" << endl;
cout << "Enter the next telephone number or enter a negative number to stop ";
cin >> n;
}
cout << "The number of fixed lines is " << cf << endl;
cout << "The number of mobile lines is " << cm << endl;
system ("PAUSE");
}
I have two problems:
I don't know how to end the program when the user enters a negative number.
Program doesn't cout "Enter the next telephone number or enter a negative number to stop " after entering the second number.
Upvotes: 1
Views: 665
Reputation: 24146
break
statementconsider following code:
int n, c=1, cm=0, cf=0;
while (c <= 15) {
std::cout << "Enter the next telephone number or enter a negative number to stop ";
std::cin >> n; // output prompt and ask for number only once per loop iteration
if (n <= 0)
break; // ends while loop if user entered incorrect value
if (n/1000000 == 39)
cm++, c++;
else if (n/1000000 == 17)
cf++, c++;
else
std::cout << "Wrong telephone number" << std::endl;
}
std::cout << "The number of fixed lines is " << cf << std::endl;
std::cout << "The number of mobile lines is " << cm << std::endl;
Upvotes: 3
Reputation: 1717
Problem 1:
break
to exit the while loop.Problem 2:
cout << "Enter a telephone number or enter a negative number to stop ";
within the while loop.Upvotes: 0