c++functionzipcode

making a function where a user inputs a zipcode


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;
}

Solution

  • #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;
    }