创建一个用户输入邮政编码的函数

问题描述 投票:0回答:1

我是一名新程序员,所以我有点困惑。如果我希望用户输入邮政编码并希望确保用户输入的数字不超过五个,我该怎么做。我是否必须创建一个 if 语句?

使用命名空间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;`
c++ function zipcode
1个回答
0
投票

是的,您可以使用 if 语句来检查用户输入的邮政编码是否包含超过五个数字。具体方法如下:

#include <iostream>
#include <string>

void address(int begin, int zipcode) {
    std::cout << begin << " Rainbow is my address. My zipcode is " << zipcode << std::endl;
}

int main() {
    int begin, zipcode;
    std::cout << "Type in the beginning numbers of your address and the zipcode: ";
    std::cin >> begin >> zipcode;

    // Check if the length of the zipcode is greater than 5
    if (std::to_string(zipcode).length() > 5) {
        std::cout << "Error: Zipcode must not contain more than five numbers." << std::endl;
        return 1; // Exit the program with an error code
    }

    address(begin, zipcode);

    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.