How to extract a float from a string in C++

1 Answer

0 votes
#include <iostream>
#include <string>
#include <regex>

int main() {
    std::string str = "The price is 148.95 dollars";

    std::regex floatRegex(R"([-+]?\d*\.\d+|\d+)");
    std::smatch match;

    if (std::regex_search(str, match, floatRegex)) {
        float number = std::stof(match.str());
        std::cout << "Extracted float: " << number << std::endl;
    }
}

  
  
/*
run:

Extracted float: 148.95
  
*/

 



answered Jul 28, 2025 by avibootz
edited Jul 28, 2025 by avibootz
...