making a function where a user inputs a zipcode

77 views Asked by At

I'm a new programmer so I'm kind of confused. If I wanted the user to type in a zipcode and want to make sure the user doesn't type more than five numbers how would I go about it. Would I have to create a if statement.

#include <iostream>
#include <string>

using namespace std; 

void address(int begin, int zipcode) { 
    cout << begin << " Rainbow is my address. My zipcode is " << zipcode << endl;
}
 
int main()
{ 
    cout << "Type in the beginning numbers of your address and the zipcode" << endl; 
    cin >> begin; 
    //cin >> zipcode;
}
1

There are 1 answers

5
Milos Stojanovic On BEST ANSWER
#include <iostream>
#include <string>

bool isValidZipCode(const std::string& zipcode) {
    return zipcode.length() <= 5;
}

void printZipCode(const std::string& zipcode) {
    if (isValidZipCode(zipcode)) {
        std::cout << "Valid zip code: " << zipcode << std::endl;
    } else {
        std::cout << "Invalid zip code: " << zipcode << std::endl;
    }
}

int main() {
    std::string zipcode;
    std::cout << "Enter a zip code: ";
    std::cin >> zipcode;

    printZipCode(zipcode);

    return 0;
}
  • The isValidZipCode function checks if the length of the zip code string is 5 or less.
  • The printZipCode function prints whether the zip code is valid or invalid based on the result of `isValidZipCode.
  • In the main function, the user is prompted to enter a zip code, and then printZipCode is called to validate and print the zip code.