Question

I have a a simple question, if I want to print a value on the same line as the output of my system time, is this possible?

char *date;
time_t timer;
timer=time(NULL);
date = asctime(localtime(&timer));
//printf("Current Date: %s", date);


  std::cout << date << ", " << randomNumber  << std::endl;

  if (file.is_open())
  {
    file << date;
    file << ", ";
    file << randomNumber;
    file << "\n";
  }

What I was hoping would happen is that I would get this as an output:

Wed Jan 16 16:18:56 2013, randomNumber

But what I do end up getting in my file is :

Wed Jan 16 16:18:56 2013
, randomNumber

Also, I just did a simple std::cout, and I notice the same result. It seems that the system forces an end line at the end of the output, is there anyway, I can supress this?

Was it helpful?

Solution

You can just replace the '\n' character in the date string (if null terminated it should be at strlen(date) - 1) with '\0' and it should print on the same line.

date[strlen(date) - 1] = '\0';

EDIT: As pointed out by Joachim strlen returns length without NULL terminator not raw allocation length so it should be -1 not -2.

OTHER TIPS

The newline character is the last character in the string returned from asctime. The simplest way to remove it is to replace it with the string terminator character '\0'.

A note about Windows: Windows have two characters for newline, carriage-return '\r' and the regular newline '\n'. So on Windows you have to terminate at the second last character. If you want your code to be portable across Windows and non-Windows platforms you have to add checks for that.

If you want to use strings you have better alternatives.

This worked for me:

#include<iostream>
#include<chrono>
#include<ctime>

using namespace std;

string getDate()
{
    chrono::system_clock::time_point tp = chrono::system_clock::now();
    time_t t = chrono::system_clock::to_time_t(tp);
    const char * tc = ctime(&t);
    string str = string {tc};
    str.pop_back();
    return str;
}

int main(){
    cout << getDate() << endl << hi;
}

Output:

Mon Dec  7 17:40:01 2015
hi

this will work:

date = date.substr(0, date.size()-1);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top