函数没有返回任何内容

时间:2015-11-13 07:02:35

标签: c++

此代码用于编程类的作业。我应该以HH:MM AM或HH:MM PM的格式输入时间并将其转换为军事时间。

我的教授希望我们编写代码,以便无论大小写都读取AM和PM(Am,pM,am,PM都可以接受)。转换函数应将标准时间作为字符串参数,将时间转换为四位军事时间格式(EX.1:10 AM应为0110小时,下午5:05应为1705小时等),以及将新军事时间的字符串返回到main函数,以便main函数可以将其写入输出。

我不再收到任何错误,但似乎当我运行程序时,我的mtime变量没有写入任何内容。我的输出只是“相应的军事时间是几小时”。有人可以帮助我发现为什么我的转换功能没有恢复军事时间吗?

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

string to24Hour(string);

int main()
{
    string stime, mtime;
    cout << "Enter time: ";
    getline (cin, stime);

    mtime = to24Hour(stime);

    cout << "Corresponding military time is " << mtime << " hours.";
    return 0;
}

string to24Hour(string time)
{
    string hour, minute, period, mtime;
    int colon, space;

    colon = time.find(":");
    space = time.find(" ");

    hour = time.substr(0, colon);
    int ih = stoi(hour);
    minute = time.substr(colon + 1, space);
    period = time.substr(space + 1);
    period = toupper(period[0]) + toupper(period[1]);

    if (period == "AM")
    {
        if (ih = 12)
            mtime = "00" + minute;
        else if (ih < 10)
            mtime = "0" + hour + minute;
        else
            mtime = hour + minute;
        return mtime;
    }
    if (period == "PM")
    {
        if (ih < 12)
        {
            ih = ih + 12;
            hour = to_string(ih);
            mtime = hour + minute;
        }
        else
            mtime = "12" + minute;
        return mtime;
    }
}

1 个答案:

答案 0 :(得分:0)

发现部分问题。当我用两个角色做那个toupper线时,它在AA中转动AM,重音超过了第二个A.因为它不是AM或PM,所以没有执行任何操作。现在一切正常!

这是更新的代码。

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

string to24Hour(string);

int main()
{
    string stime, mtime;
    cout << "Enter time: ";
    getline (cin, stime);

    mtime = to24Hour(stime);

    cout << "Corresponding military time is " << mtime << " hours.";
    return 0;
}

string to24Hour(string time)
{
    string hour, minute, period, mtime;
    int colon, space;

    colon = time.find(":");
    space = time.find(" ", 4);

    hour = time.substr(0, colon);
    int ih = stoi(hour);
    minute = time.substr(colon + 1, 2);
    period = time.substr(space + 1);
    period = toupper(period[0]);

    if (period == "A")
    {
        if (ih < 10)
            mtime = "0" + hour + minute;
        else if (ih = 12)
            mtime = "00" + minute;
        else
            mtime = hour + minute;
        return mtime;
    }
    if (period == "P")
    {
        if (ih < 12)
        {
            ih = ih + 12;
            hour = to_string(ih);
            mtime = hour + minute;
        }
        else
            mtime = "12" + minute;
        return mtime;
    }
}