繁体   English   中英

如何在 C++ 中将月份名称(3 个字母缩写)转换为月份编号,反之亦然? [等候接听]

[英]How can I convert month names (3 letter abbreviation) to month number, and vice versa, in C++? [on hold]

我是编码/编程的新手,我在 C++ 参加了我的第一门编程课程。 到目前为止,这是我的代码。 我正在尝试将月份名称转换为月份编号,反之亦然,具体取决于用户选择输入的内容。 我不确定如何继续前进。 出现的一个问题是我的 if 循环。 我最初有类似 if (response == m) 但后来我意识到问题可能是因为 m 是一个 int 而 response 是一个字符串。 所以我不确定如何调和这一点。

#include <iostream>
#include <string>
using namespace std;

int main()
{
    int m;
    string response;
    string months[] = { "Jan", "Feb", "Mar", "Apr", "May",
                       "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
    cout << "Enter a month number or the first three letters of a month: \n";
    cin >> response;

    if (response == )
    {
        cout << "You selected " << months[m - 1] << endl;
    }
    else 
    {
        for (int i = 0; i < 12; i++)
        {
            if (response == months[i])
            {
                cout << "You selected " << i + 1 << endl;
            }

        }

    }

    return 0;
}

据我了解,您正在寻找 function 之类的

bool isNumberBetween1And12(string str, int &m) {
    try {
        const int temp{stoi(str)};
        if (to_string(temp) == str && temp >= 1 && temp <= 12) {
            m = temp;
            return true;
        }
    } catch (...) {}
    return false;
}

此 function 检查输入是否为 1 到 12 之间的数字。如果是,则返回 true 并将m设置为该值。 如果不是,则返回 false。 如果stoi无法将字符串转换为任何数字,则它会引发异常。 比较

to_string(temp) == str

检查字符串是否只包含数字。

这是一个如何使用它的示例

#include <array>
#include <iostream>
#include <string>
using std::array;
using std::string;
using std::cin;
using std::cout;
using std::to_string;
using std::stoi;

bool isNumberBetween1And12(string str, int &m) {
    try {
        const int temp{stoi(str)};
        if (to_string(temp) == str && temp >= 1 && temp <= 12) {
            m = temp;
            return true;
        }
    } catch (...) {}
    return false;
}

int main() {
    const array<string, 12> months = { "Jan", "Feb", "Mar", "Apr", "May",
                                 "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
    string response;
    cout << "Enter a month number or the first three letters of a month: \n";
    cin >> response;

    int m;
    if (isNumberBetween1And12(response, m)) {
        cout << "You selected " << months[m - 1] << '\n';
    } else {
        for (int i = 0; i < 12; i++) {
            if (response == months[i]) {
                cout << "You selected " << i + 1 << '\n';
            }
        }
    }
    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM