c++ - 如何将时间字符串(M:SS)转换为float

标签 c++ string c++11

所以我很难弄清楚这次如何转换: 4:27.47
转换为秒的浮点值。
如果您需要更多详细信息,请随时询问。

最佳答案

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

以下编辑使代码也适用于格式(MM:SS)
#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
}

关于c++ - 如何将时间字符串(M:SS)转换为float,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59978640/

相关文章:

c++ - 为什么 std::tuple 会破坏 C++ 中的小型结构调用约定优化?

c++ - 对句子进行标记时,字符串结尾有哪些类型的指示符?

c# - 字符串格式 : remove the last underscore and the following characters

c# - 如何找到字符串中所有可能的子串?

c++ - 链接时间优化与多线程支持冲突

c++ - 使用 _1 和 _2 占位符运行 make 因 boost::bind 失败...?

c++ - C++中流的优点是什么?

c++ - C++ : What is the best practice of error handling (without exceptions) while reading the file

成员模板的 C++ 混淆属性名称

c++ - 使用聚合初始化和成员初始化器初始化结构