c++systemtime

Prevent endline after printing system time


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?


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.