Home > other >  Conversion from char* to std::string gives wrong symbols
Conversion from char* to std::string gives wrong symbols

Time:10-18

My code is:

std::string get_time() {
    char buf[20];
    std::time_t timestamp = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
    strftime(buf, 20, "%d.%m.%Y %H:%M:%S", std::gmtime(&timestamp));
    
    std::cout<<buf<<std::endl;
    return std::string(buf, 20);
}

...

auto timestamp = get_time().c_str();
std::cout<<timestamp<<std::endl;

It should return current datetime in string format. But what I get is:

17.10.2022 11:12:46
1!`u�I��22 11:12:46

So, the conversion beween char* and string works wrong. How can I fix it? Thanks in advance!

CodePudding user response:

First of all, get_time() returns a std::string. Because nothing references this string, it gets deleted at the end of the line. Then, calling get_time().c_str() keeps a pointer to that string (see std::basic_string<CharT,Traits,Allocator>::c_str on cppreference). However, that string isn't guaranteed to exist. Other processes have overwritten some of that memory, using it, and that is why you get those characters. You don't need to call get_time.c_str(), you can just output the std::string directly:

std::string get_time() {
    char buf[20];
    std::time_t timestamp = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
    strftime(buf, 20, "%d.%m.%Y %H:%M:%S", std::gmtime(&timestamp));
    
    std::cout << buf << std::endl;
    return std::string(buf, 20);
}

...

auto timestamp = get_time();
std::cout << timestamp< < std::endl;
  •  Tags:  
  • c
  • Related