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
9,5676 gold badges39 silver badges47 bronze badges
asked Jul 15, 2020 at 15:00
6
  • 8
    line.substr(0, 9).c_str()? As is described in the documentation of std::atof, it accepts const char*, and std::string is not that. Commented Jul 15, 2020 at 15:00
  • 5
    std::stof? Includes better validation and allows better error handling. Commented Jul 15, 2020 at 15:01
  • 5
    "set11.c" is a pretty odd name for a C++ source file. Commented Jul 15, 2020 at 15:03
  • 2
    std::stod if doubles are wanted. Commented Jul 15, 2020 at 15:11
  • @AlgirdasPreidžius Thanks alot! Commented Jul 15, 2020 at 15:22

1 Answer 1

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;
answered Jul 15, 2020 at 15:25
Sign up to request clarification or add additional context in comments.

1 Comment

If stod could take a string_view this would be easy and great. Alas...

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.