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?
#include <iostream>
#include <string>
usingnamespace 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;
}
}
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:
elseif (zipArea == "606")
cout << "You are in the 606 area and your shipping charge is $30" << endl;
elseif (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.
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 usingnamespace std; at the top of code and instead to explicitly identify functions I call from the std namespace.