I have to create a program that requires the user to enter the zip code. The zip code must be 5 digits. I know how to do that using if statement and string.length(). What I don't know how to do is how to make sure the program only inputs and accepts zip codes that start with 606 and 605.

Here's my code so far

#include <iostream>
#include <string>

using namespace std;

int main()
{
	cout << "Please enter zip code: ";
	string = zipCode;
	getline(cin,zipCode);

	if (zipCode.length() == 5 && )
	{

	}
	
	else
		cout << "Please enter a 5 digit Zip Code ";

I have to use a string function

Recommended Answers

All 3 Replies

You call this:

string = zipCode;

before you have defined zipcode. Did you mean to say

string zipCode;

?

Also, you can access individual characters in a string with the [] operator. That is, you can check if the first digit is a '6' by doing:

if(yourString[0] == '6')

Good luck,

David

Thanks you fixed it.

below is a code, hope it helps.

#include <iostream>
#include <string>

using namespace std;

int main()
{

string str1 = "606", str2 = "605" str3;
size_t pos;

cout << "Please enter zip code: ";
string = zipCode;
getline(cin,zipCode);

pos = zipCode.find("606");
str3 = zipCode.substr(pos + 3);

if (str3 == str1 || str3 == str2 )
{

cout<< "OK"<<endl;
}

else
cout << "Please enter a 5 digit Zip Code ";

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.