Reputation: 327
I am creating a time class (string base) for my school project! I get a pointer character for the time!I have a function to normalize the time if it is weird.
in normalize function I have a character array to store the correct time but when I want to Assign the character array to the pointer character it is going false!
char st[10] = "", sh[3] = "", sm[3] = "", ss[3] = "";
itoa(hour, sh, 10);
itoa(minute, sm, 10);
itoa(second, ss, 10);
if(hour<10){strcat(st, "0");}
strcat(st, sh);strcat(st, ":");
if(minute<10){strcat(st, "0");}
strcat(st, sm);strcat(st, ":");
if(second<10){strcat(st, "0");}
strcat(st, ss);strcat(st, "");
stime = st;
stime
is pointer character which save the time in class.
when I want to use value of stime
I get very weird result. stime get the value of last class stime
. for example I have this code:
time a("1:50:0"), b("4:5:10");
a.print();
b.print();
but I get 04:05:10
for two classes and I don't know why!
If you need the rest of code I upload it here: Google Drive link to file
Upvotes: 0
Views: 95
Reputation: 2221
When I compile your code I get the following warning:
warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
time(char *t = "0:0:0"):stime(t){normalize(-1, -1, -1);}
This is what is causing your issue.
"0:0:0"
in C++ is a const char[5]
which can be converted implicitly to a const char *
but not to a simple char *
, which is the storage type you have chosen for time
.
As others have mentioned, in C++ you should use std::string
rather than char*
.
As a general rule you should never ignore warnings unless you are sure you know why they are appearing. Often, as in this case, they are telling you that your code is not going to behave in the way you'd expect.
Upvotes: 1
Reputation: 30136
You can try this as a C++ solution:
#include <sstream>
#include <iomanip>
#include <iostream>
using namespace std;
string GetComponent(int value)
{
ostringstream oss;
oss << setfill('0') << setw(2) << value;
return oss.str();
}
void PrintTime(int hh,int mm,int ss)
{
cout << GetComponent(hh) << ':' << GetComponent(mm) << ':' << GetComponent(ss) << endl;
}
Usage example:
PrintTime(1,2,3);
PrintTime(1,2,33);
PrintTime(1,22,33);
PrintTime(11,22,33);
Upvotes: 1