How to use substr with atof?

195 views Asked by At

Reading from a .txt file, I would like to convert some values from a file, converting a string into doubles. Normally, I can print the desired values:

string line;
ifstream f; 
f.open("set11.txt");

if(f.is_open()) {

    for(int i = 0; i < 3; i++) {
        
        getline(f, line);
        cout << "Voltage " << i  << ": " << line.substr(0, 9) << endl;
    }
}

f.close();

Terminal:

Voltage 0: 5.0000000
Voltage 1: 8.0000000
Voltage 2: 1.1000000

However, when I try to make them double, I replace the command with

cout << "Voltage " << i  << ": " << atof(line.substr(0, 9)) << endl;

and I get the following error:

    Voltage 0: Error: atof parameter mismatch param[0] C u C:\Users\User\Desktop\Physics\FTE\Root\set11.c(26)
(class G__CINT_ENDL)9129504
*** Interpreter error recovered ***

Any clues here? Sorry if I'm missing something obvious, I'm quite new to C++

1

There are 1 answers

1
Waqar On

The problem is that atof() takes a const char* as parameter, while you are passing std::string

Use std::stod instead:

   cout << "Voltage " << i  << ": " << stod(line.substr(0, 9)) << endl;

Or convert your std::string to a const char* using the .c_str() function and then pass that as parameter to atof:

   cout << "Voltage " << i  << ": " << stod(line.substr(0, 9).c_str()) << endl;