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

时间:2018-04-23 05:56:18

标签: c++ arrays

我正在尝试将月份的实际名称显示到输出而不是与其关联的数字。基本上我必须将月份显示为字符串而不是数字。我不确定如何成功转换为字符串。它在下面用数字代替它,但是我无法让它在屏幕上显示字符串。

我需要有句子:“输入1月份的降雨量(以英寸为单位)” 以及:“ 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;
}

1 个答案:

答案 0 :(得分:1)

你正在隐藏你的阵列几个月&#39;通过名为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;
}