0

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++

Waqar
  • 8,558
  • 4
  • 35
  • 43
  • 8
    `line.substr(0, 9).c_str()?` As is described in the documentation of [`std::atof`](https://en.cppreference.com/w/cpp/string/byte/atof), it accepts `const char*`, and `std::string` is not that. – Algirdas Preidžius Jul 15 '20 at 15:00
  • 5
    [`std::stof`](https://en.cppreference.com/w/cpp/string/basic_string/stof)? Includes better validation and allows better error handling. – Some programmer dude Jul 15 '20 at 15:01
  • 5
    "set11.c" is a pretty odd name for a C++ source file. – molbdnilo Jul 15 '20 at 15:03
  • 2
    `std::stod` if doubles are wanted. – sweenish Jul 15 '20 at 15:11
  • @AlgirdasPreidžius Thanks alot! – Stamatis Tzanos Jul 15 '20 at 15:22
  • This doesn't address the question, but get in the habit of initializing objects with meaningful values rather than default initializing them and immediately overwriting the default value. In this case, that means changing `ifstream f; f.open("set11.txt");` to `ifstream f("set11.txt");`. Also, you don't need to call `f.close();`. The destructor will do that. – Pete Becker Jul 15 '20 at 17:51

1 Answers1

2

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;
Waqar
  • 8,558
  • 4
  • 35
  • 43