Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,922 questions

51,855 answers

573 users

How to extract hours, minutes and second from string in C++

3 Answers

0 votes
#include <iostream>
#include <sstream>
#include <iomanip>

int main() {
    std::string str = "11:28:34";

    std::istringstream ss(str);
    std::tm tm = {};  // Initialize to all zeros
    ss >> std::get_time(&tm, "%H:%M:%S");

    if (ss.fail()) {
        std::cerr << "Invalid time format\n";
        return 1;
    }

    int hours = tm.tm_hour;
    int minutes = tm.tm_min;
    int seconds = tm.tm_sec;

    std::cout <<  hours << ":" << minutes << ":" << seconds;
}



 
/*
run:
 
11:28:34
 
*/

 



answered Dec 27, 2023 by avibootz
0 votes
#include <iostream>
#include <cstdio>

int main() {
    std::string str = "11:28:34";

    int hours, minutes, seconds;
    
    if (std::sscanf(str.c_str(), "%d:%d:%d", &hours, &minutes, &seconds) != 3) {
        std::cerr << "Invalid time format\n";
        return 1;
    }

    std::cout <<  hours << ":" << minutes << ":" << seconds;
}




 
/*
run:
 
11:28:34
 
*/

 



answered Dec 27, 2023 by avibootz
0 votes
#include <iostream>
#include <string>
#include <vector>

int main() {
    std::string str = "11:28:34";

    std::vector<std::string> time_parts;
    size_t pos = 0;
    
    while ((pos = str.find(":", pos)) != std::string::npos) {
        time_parts.push_back(str.substr(0, pos));
        str.erase(0, pos + 1);
    }
    time_parts.push_back(str);  // Add the seconds

    if (time_parts.size() != 3) {
        std::cerr << "Invalid time format\n";
        return 1;
    }

    int hours = std::stoi(time_parts[0]);
    int minutes = std::stoi(time_parts[1]);
    int seconds = std::stoi(time_parts[2]);

    std::cout <<  hours << ":" << minutes << ":" << seconds;
}




 
/*
run:
 
11:28:34
 
*/

 



answered Dec 27, 2023 by avibootz

Related questions

1 answer 109 views
1 answer 140 views
1 answer 104 views
2 answers 152 views
2 answers 162 views
...