C++ Code to exclude integers

This code works right. What I am trying to do is add some more code that returns an INVALID message if someone doesn't start with 605, 606 or 607. What line of code do I need and where does it go?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <string>
using namespace std;

int main()
{
string zip, zipArea;

cout << "Enter a 5-digit zip code starting with 605, 606 or 607: ";
cin >> zip;

while (zip.length() != 5)
{
cout << "Invalid zip code. Please enter a 5-digit zip code starting with 605, 606 or 607: ";
cin >> zip;
}

zipArea = zip.substr(0, 3);

if (zipArea == "605") {
	cout << "You are in the 605 area and your shipping charge is $25" << endl;
}
else {
	if (zipArea == "606") {
	cout << "You are in the 606 area and your shipping charge is $30" << endl;
	}
else {
	if (zipArea == "607") {
	cout << "You are in the 607 area and your shipping charge is $40" << endl;
	}
}
system ("pause");
return 0;
}
}
Last edited on
A final else?
See all those slightly confused if else groups? Stick another else on the end, along the lines of

1
2
3
4
else
{
  std::cout << "INVALID";
}
1
2
3
4
5
6
7
8
9
if (zipArea == "605")
	cout << "You are in the 605 area and your shipping charge is $25" << endl;
// you should just use `else if` instead of `else` with an `if` inside:
else if (zipArea == "606")
	cout << "You are in the 606 area and your shipping charge is $30" << endl;
else if (zipArea == "607")
	cout << "You are in the 607 area and your shipping charge is $40" << endl;
else 
	cout << "Invalid zip area" << endl; // your error message here. 
I tried adding

1
2
3
4
else
{
std::cout << "INVALID";
}


right before "system ("pause") but it would not compile. And I am not sure what "std::cout" means - I am very new at this.
see http://www.cprogramming.com/tutorial/string.html
It gives the following example:
1
2
3
4
string my_string = "abcdefghijklmnop";
string first_ten_of_alphabet = my_string.substr(0, 10);
cout<<"The first ten letters of the alphabet are "
    <<first_ten_of_alphabet;

After that you can check
1
2
3
4
5
while (first_three_of_string !="605" && first_three_of_string !="606" && first_three_of_string!="607")
{
cout << "error"
cin >> zip
}
Every else must be associated with a preceeding if

Sticking one in just before the system("pause") won't help, as it has no preceeding if. You already made that stack of if else; you just need one more else in there.


std::cout means the cout function in the std namespace. It's my habit not to put using namespace std; at the top of code and instead to explicitly identify functions I call from the std namespace.
Last edited on
Topic archived. No new replies allowed.