1
votes

Comment convertir une chaîne de temps (M: SS) en float

J'ai donc du mal à trouver comment convertir cette fois: 4:27.47

en une valeur flottante de secondes.

Si vous avez besoin de plus de détails, n'hésitez pas à demander.


0 commentaires

4 Réponses :


3
votes
#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
}

2 commentaires

cela ne fonctionne que si la minute ne contient qu'un seul chiffre. Et la chaîne est M: SS, pas H: MM, donc votre résultat est 60 fois plus grand que la valeur correcte


@phuclv l'OP a dit (M: SS). De toute façon j'ai fourni un ajout. Merci



1
votes
#include<stdio.h>
int main()
{
    double minute, second;
    scanf("%lf : %lf", &minute, &second);
    printf("%f\n", minute * 60 + second);
}

0 commentaires

-1
votes

Vous pouvez diviser la chaîne avec les deux-points (:), puis convertir la chaîne en flottant et calculer le nombre total de secondes comme suit

#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;

}



0
votes

Solution un peu verbeuse, mais ça marche quand les heures sont données ou non:

(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;
}


0 commentaires