The C++ standard C functions compile equally across platforms

  • 2020-06-12 10:06:28
  • OfStack

introduce

The ANSI organization defines the C standard and standard library functions.

Advantages of using standard C functions:

Using the standard C function is supported on any platform so that the compilation and run of Windows on the same source code produces the same result as the compilation and run on Linux without changing the code.

Random number (rand)

Generate random Numbers (1~100) in a specified range


#include <stdio.h>
#include <stdlib.h>
int main()
{
 for (int i=0; i<10; i++)
 {
 printf("%d\n", rand()%100);
 }
}

To solve this problem, srand was used to set one seed (seed), and the seed was different each time it was started.


#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
 srand(time(NULL));
 for (int i=0; i<10; i++)
 {
 printf("%d\n", rand()%100);
 }
}

Time function (time)

Gets the current timestamp (s) in seconds from 1970-01-01 00:00:00


#include <stdio.h>
#include <time.h>
int main()
{
 time_t ts = time(NULL);
 printf("%d\n", (int)ts);
}

Get year, month, day, minute, second, and week by timestamp


#include <stdio.h>
#include <time.h>
int main()
{
 time_t ts = time(NULL);
 tm time = *localtime(&ts);
 int year = time.tm_year + 1900;
 int month = time.tm_mon + 1;
 int day = time.tm_mday;
  int hour = time.tm_hour;
 int min = time.tm_min;
 int sec = time.tm_sec;
 int week = time.tm_wday ;
 return 1;
}

Gets the time_t timestamp by year, month, day, hour and second


#include <stdio.h>
#include <time.h>
int main()
{
 // The time for 2017-07-15 21:38:30
 tm time = {0};
 time.tm_year = 2017 - 1900;
 time.tm_mon = 7 -1;
 time.tm_mday = 15;
  time.tm_hour = 21;
 time.tm_min = 38;
 time.tm_sec = 30;
 time_t ts = mktime(&time);
 // Get the day of the week 
 tm time1 = *localtime(&ts);
 printf(" weeks %d\n", time1.tm_wday);
 return 1;
}

conclusion


Related articles: