简体   繁体   中英

How to convert a string of a time (M:SS) to float

So I'm having trouble figuring out how to convert this time: 4:27.47

into a float value of seconds.

If you need any more details, feel free to ask.

#include<string>
#include<iostream>
int main(){
    std::string str{ "4:27.47"};//The given string
    float secs {std::stof(str) * 60+std::stof(str.substr(2))};//Your float seconds
    std::cout<<secs;//Display answer
}

The following edit makes the code works on the format (MM:SS) too

#include<string>
#include<iostream>
int main(){

    size_t pos{};//To get the position of ":"
    std::string str{ "4:27.47"};//The given string
    float secs {std::stof(str, &pos) * 60+std::stof(str.substr(pos+1))};//Your float seconds
    std::cout<<secs;//Display answer
}
#include<stdio.h>
int main()
{
    double minute, second;
    scanf("%lf : %lf", &minute, &second);
    printf("%f\n", minute * 60 + second);
}

A bit verbose solution, but it works when hours are given or not:

(HH:MM:SS.Milli) || (MM:SS.Milli) || (SS.Milli) || (.Milli)

double parse_text_minutes_to_double(std::string original)
{
    std::vector<std::string> hms;
    std::size_t pos;
    while(std::count(original.begin(), original.end(), ':') )
    {
        pos  = original.find(':');
        hms.push_back(original.substr(0, pos));
        original = original.substr(pos+1);
    }

    int minutes_hours{};
    double sec_and_milli = std::stof(original);
    int iteration_count{};
    while (!hms.empty())
    {
        ++iteration_count;
        int seconds_iteration = std::stoi(hms.back()) * std::pow(60, iteration_count);
        hms.pop_back();
        minutes_hours += seconds_iteration;
    }
    return minutes_hours + sec_and_milli;
}

int main()
{
    std::string original("1:1:20.465");
    double result = parse_text_minutes_to_double(original);

    std::cout << result << std::endl;
}

You can split the string with the colon (:) and then convert the string to float and calculate the total seconds as follows

#include <iostream>
#include <cstdlib> 

using namespace std;

int main(){

    string time = "4:27.47";
    string minutes = "";
    string seconds = "";
    string temp = "";
    float m, s;

    for(int i=0; i<time.length(); i++){
        if(time[i]==':'){
            minutes = temp;
            temp = "";
        }
        else
            temp += time[i];
        if(i==time.length()-1)
            seconds = temp;
    }

    // casting string to float
    m = atof(minutes.c_str());
    s = atof(seconds.c_str());

    float total = m*60 + s;
    cout << total;

    return 0;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM