![](/img/trans.png)
[英]Have been trying to convert 12-hour clock format into 24-hour clock format in c++
[英]I am trying to convert a 12 hour time format to 24 hour time format ,and store it in a string but i am not able to store it in a string
所以这是我的 function 名称转换器,它返回新字符串。 但我不知道如何将这个东西存储在字符串中。 请帮助我为什么会出现编译错误。 strcpy 不工作。 以及如何将变量 hh 存储在我的字符串中?
string converter(string str)
{
string newstring; /// Creating a new string which I return from here
int h1 = (int)str[1] - '0';
int h2 = (int)str[0] - '0';
int hh = (h2 * 10 + h1 % 10);
// If time is in "AM"
if (str[5] == 'A')
{
if (hh == 12)
{
string stringone("00");
strcpy(newstring,stringone); //getting error caanot convert
for (int i=2; i < 5;i++)
newstring[i]=str[i];
}
else
{
for (int i=0; i < 5; i++)
newstring[i]=str[i];
}
}
// If time is in "PM"
else
{
if (hh == 12)
{
char stringtwo="12";
strcpy(newstring,stringtwo);
for (int i=2; i < 5; i++)
newstring[i]=str[i];
}
else
{
hh = hh + 12;
newstring.push_back(hh); /// Is this correct?
for (int i=2;i < 5;i++)
newstring[i]=str[i];
}
}
return newstring;
}
尝试这个:
#include <iostream>
#include <cstdlib>
#include <stdlib.h>
#include <string>
//converts time in hh:mm am/pm string format & string length should be 8 for function to work properly
std::string converter(std::string str){
std::string newstring;
std::string amOrpm = {str.at(6), str.at(7)};
char hr[2] = {str.at(0), str.at(1)};
int hour = atoi(hr);
//if time is pm convert to 24hr format
if(amOrpm == "pm"){
hour += 12;
newstring = std::to_string(hour);
for(int i = 0; i < newstring.length(); i++)
str.at(i) = newstring.at(i);
for(int i = 6; i < str.length(); i++)
str.at(i) = NULL;
return str;
}else
return str;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.