尝试从整数转换为字符串的月份

Trying to convert from integer to string for month

本文关键字:字符串 转换 整数      更新时间:2023-10-16

我试图让月份的实际名称显示在输出中,而不是与之关联的数字。基本上,我必须将月份显示为字符串而不是数字。我不确定如何成功转换为字符串。它在下面工作,数字在它的位置,但我只是无法让它在屏幕上显示字符串。

我需要有一句话:"输入一月份的降雨量(以英寸为单位("以及:">1月份的最大降雨量为12英寸">

这是我到目前为止的代码(更新帖子以删除不相关的代码(:

// Declare const variables
const int TOTALMONTHS = 12;
// Declare array for months and rainfall
string months[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
double rainFall[TOTALMONTHS];
// Declare functions
double getLowest(double[], int, int&); // returns the lowest value, provides the index of the lowest value in the last parameter.
double getHighest(double[], int, int&); // returns the higest value, provides the index of the highest value in the last parameter.
int main()
{
    int subscript;
    // Get the rainfall for each month.
    for (int months = 0; months < TOTALMONTHS; months++)
    {
        // Get this month's rainfall.
        cout << "Enter the rainfall (in inches) for month #";
        cout << months[months] << ": ";
        cin >> rainFall[months];
        // Validate the value entered.
    }
    // The subscript variable will be passed by reference to the getHighest and getLowest functions.
    // Display the largest amount of rainfall.
    cout << "The largest amount of rainfall was ";
    cout << getHighest(rainFall, TOTALMONTHS, subscript)
        << " inches in month ";
    cout << (subscript + 1) << "." << endl;
    // Display the smallest amount of rainfall.
    cout << "The smallest amount of rainfall was ";
    cout << getLowest(rainFall, TOTALMONTHS, subscript)
        << " inches in month ";
    cout << (subscript + 1) << "." << endl << endl;
    // End of program
    system("pause");
    return 0;
}

你用一个也叫months的循环变量隐藏了带有月份名称(months(的数组 - 在给定的作用域中,你只能有一个名为months的变量。最好将它们都重命名,然后您只需将数组的值打印在您现在使用的索引处作为数字(在 + 1 之前(:

string monthNames[TOTALMONTHS] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
int main()
{
    int subScript;
    //...
    for (int month = 0; month < TOTALMONTHS; month++)
    {
        // Get this month's rainfall.
        cout << "Enter the rainfall (in inches) for month ";
        cout << monthNames[month] << ": ";
        cin >> rainFall[month];
        //...
    }
    //...
    cout << "The largest amount of rainfall was ";
    cout << getHighest(rainFall, TOTALMONTHS, subScript)
        << " inches in month ";
    cout << monthNames[subScript] << "." << endl;
    //...
    system("pause");
    return 0;
}