In this guide, you will learn what is ctime() function is in C++ programming and how to use it with an example.
1. ctime() Function Overview
The ctime() function in C++ is used to convert a given time_t value to its human-readable string representation. The function returns a string that represents the current local date and time in the format: "Www Mmm dd hh:mm:ss yyyy". It's a convenient way to quickly convert a time_t value to a formatted string without manually converting it to a tm structure first. The function is included in the <ctime> header.
Signature:
const char* ctime(const time_t* timep);
Parameters:
- timep: Pointer to a time_t value representing the number of seconds elapsed since the epoch (00:00:00, January 1, 1970, Coordinated Universal Time).
2. Source Code Example
#include <iostream>
#include <ctime>
int main() {
std::time_t t;
std::time(&t);
// Convert time_t value to a human-readable string
std::cout << "Current date and time: " << ctime(&t);
return 0;
}
Output:
Current date and time: Www Mmm dd hh:mm:ss yyyy Note: The actual output will depend on the current date and time.
3. Explanation
1. We first obtain the current time using the time() function and store it in a time_t variable.
2. The ctime() function is then used to convert this time_t value directly to its corresponding human-readable string representation.
3. The resulting string, which provides the current date and time, is printed to the console.
Comments
Post a Comment