Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove the newline from asctime()

Tags:

c++

newline

I want to get rid of the new line that asctime() gives me after the time

string str;
time_t tt;
struct tm * ti;
time(&tt);
ti = localtime(&tt);
str = asctime(ti);
for (int i = 0; i < 2; i++)
    cout << str;

the output is

fri apr 26 00:59:07 2019
fri apr 26 00:59:07 2019

but i want it in this form

fri apr 26 00:59:07 2019fri apr 26 00:59:07 2019
like image 844
Ray Xerxes Avatar asked Apr 25 '19 23:04

Ray Xerxes


2 Answers

Since the newline is the final character, all you have to do is remove the final character in the string. You can do this by calling pop_back

str.pop_back();

On Windows, a newline is \r\n BUT \n is the platform independent newline character for C and C++. This means that when you write \n to stdout in text mode the character will be converted to \r\n. You can just use \n everywhere and your code will be cross platform.

like image 181
Indiana Kernick Avatar answered Nov 19 '22 11:11

Indiana Kernick


Removing the last characters of the string as per Kerndog73's answer will work, but since you're using C++, you have a better solution available: The std::put_time() stream manipulator:

#include <iomanip>
#include <sstream>

// ...

auto tt = time(nullptr);
auto* ti = localtime(&tt);
std::stringstream sstream;
sstream << std::put_time(ti, "%c");
for (int i = 0; i < 2; i++)
    cout << sstream.str();

If you don't need to store the time as a string, you can just print it out directly:

auto tt = time(nullptr);
auto* ti = localtime(&tt);
for (int i = 0; i < 2; i++)
    cout << std::put_time(ti, "%c");
like image 35
Nikos C. Avatar answered Nov 19 '22 13:11

Nikos C.