簡體   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