'I have a text file and I only want to extract the numbers from each line, how do I do that?

Say I have a text file of the form:

Re_o,41.03432927885793
Re_i,62.943980961182625
Pr,0.6311803721661048
ecc_ratio,0.052136775793810645
r_i,0.44205861426671267

And I only want to extract the numbers on each line in c++. How do I do that?

c++


Solution 1:[1]

There are a few different ways you can approach this:

You can use std::getline() to read each line, and use std::istringstream to parse each line:

std::ifstream inFile("input.txt");
std::string line;
while (std::getline(inFile, line))
{
    std::istringstream iss(line);
    iss.ignore(std::numeric_limits<std::streamsize>::max(), ',');
    double value;
    iss >> value;
    // use value as needed...
}

Online Demo

Alternatively, you can parse each line manually:

std::ifstream inFile("input.txt");
std::string line;
while (std::getline(inFile, line))
{
    double value = std::stod(line.substr(line.find(',')+1));
    // use value as needed...
}

Online Demo

Or, you can simply read the values directly from the std::ifstream, ignoring everything else you don't want:

std::ifstream inFile("input.txt");
double value;
while (
    inFile.ignore(std::numeric_limits<std::streamsize>::max(), ',') &&
    inFile >> value
    )
{
    // use value as needed...
}

Online Demo

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1