gpt4 book ai didi

c++ - 我可以将 char*(月份)与字符串(二月)进行比较吗?如果没有,我该怎么做呢?

转载 作者:行者123 更新时间:2023-11-28 07:07:47 25 4
gpt4 key购买 nike

我希望该程序能够运行,以便我可以将任何措辞的月份转换为其等效数字。

#include <iostream>
using namespace std;

int main()
{
char month[20];
int INT_month;

cout << "Enter a month: (ex. January, February)";
cin >> month; // Let's say the input is February

if (month == "February")
INT_month = 2;

cout << "The month in its' integral form is " << INT_month << endl;
// INT_month = 2130567168 // WHY DOES IT DO THIS????

return 0;
}

最佳答案

一种方法是创建月份名称的 vector,并使用查找索引加一作为月份编号:

vector<string> months = {
"january", "february", "march", ...
};
string search = "march";
auto pos = find(months.begin(), months.end(), search);
if (pos != months.end()) {
cout << "Month number: " << distance(months.begin(), pos) + 1 << endl;
} else {
cerr << "Not found" << endl;
}

这会打印 3 ( demo on ideone )。

关于c++ - 我可以将 char*(月份)与字符串(二月)进行比较吗?如果没有,我该怎么做呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21506436/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com