Apr 20, 2020 at 5:51pm UTC
I switched from DevC++ to Microsoft Visual Studio while working on a project.
MVS suggested that I change the localtime() to localtime_s(), else it threw an error.
I did some changing around but the output comes up in some gibberish language.
I tried changing from using unicode character set to multi-byte character set but the output still persist.
Can someone please give me some advice on changes I should make?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
#include <string>
#include <iostream>
#include <time.h>
LPCSTR loopStartTime()
{
time_t rawtime = time(0);
tm timeinfo{};
char buffer[35];
static int counter;
time(&rawtime);
localtime_s(&timeinfo, &rawtime); // get local time
// covert time to string
strftime(buffer, 30, "loop start []: %i:%m:%s%p.\n\n" , &timeinfo);
static string str = buffer;
string str1 = to_string(counter);
str.insert(12, str1);
counter++;
return str.c_str();
}
Last edited on Apr 20, 2020 at 5:52pm UTC
Apr 21, 2020 at 3:50am UTC
Look REAL close at your strftime format string. I, M and S. not i, m and s.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
#include <iostream>
#include <ctime>
#include <cstring>
#include <string>
int main()
{
const size_t strSize = 255;
time_t t = time(NULL);
tm time_now;
localtime_s(&time_now, &t);
char cstr[strSize] = "" ;
strftime(cstr, strSize, "loop start []: %I:%M:%S%p.\n\n" , &time_now);
std::string str = cstr;
// display the time
std::cout << str << '\n' ;
}
Compiles just fine with MSVC 2019.
Why bother with a std::string just to add a number when you can use sprintf_s and concatenate that to your time C string.
For that matter the return type should be PCSTR, not LPCSTR. There are no long pointers in 32/64 bit Windows. long pointers are an artifact of 16-bit Windows.
Last edited on Apr 21, 2020 at 3:58am UTC