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
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.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With