fork download
  1. #include <iostream>
  2. #include <string.h>
  3.  
  4. int main()
  5. {
  6. {
  7. printf("With STRTOK :\n");
  8.  
  9. char str[] = "2019-12-24 09:00:00";
  10.  
  11. char separators[] = "- :";
  12. const size_t MAX_VALUES = 6;
  13. int values[MAX_VALUES];
  14. size_t valuesCount = 0;
  15.  
  16. char *p = strtok( str, separators );
  17. while ( p != NULL && valuesCount < MAX_VALUES )
  18. {
  19. values[ valuesCount++ ] = atoi(p);
  20. p = strtok( NULL, separators );
  21. }
  22.  
  23. for ( size_t i = 0; i < valuesCount; i++ )
  24. {
  25. printf( "%d\n", values[ i ] );
  26. }
  27. }
  28.  
  29. {
  30. printf("\n\nWith STRTOK_R :\n");
  31.  
  32. char str[] = "2019-12-24 09:00:00";
  33.  
  34. char separators[] = "- :";
  35. const size_t MAX_VALUES = 6;
  36. int values[MAX_VALUES];
  37. size_t valuesCount = 0;
  38.  
  39. char *p = str;
  40. char *t;
  41.  
  42. while ( ( t = strtok_r( p, separators, &p ) ) && valuesCount < MAX_VALUES )
  43. {
  44. values[ valuesCount++ ] = atoi(t);
  45. }
  46.  
  47. for ( size_t i = 0; i < valuesCount; i++ )
  48. {
  49. printf( "%d\n", values[ i ] );
  50. }
  51. }
  52.  
  53. {
  54. printf("\n\nWith SSCANF :\n");
  55.  
  56. char str[] = "2019-12-24 09:00:00";
  57.  
  58. const size_t MAX_VALUES = 6;
  59. int values[MAX_VALUES];
  60.  
  61. if ( sscanf( str, "%d-%d-%d %d:%d:%d", &values[0], &values[1], &values[2], &values[3], &values[4], &values[5] ) == MAX_VALUES )
  62. {
  63. for ( size_t i = 0; i < MAX_VALUES; i++ )
  64. {
  65. printf( "%d\n", values[ i ] );
  66. }
  67. }
  68. }
  69.  
  70. return 0;
  71. }
Success #stdin #stdout 0s 4304KB
stdin
Standard input is empty
stdout
With STRTOK :
2019
12
24
9
0
0


With STRTOK_R :
2019
12
24
9
0
0


With SSCANF :
2019
12
24
9
0
0