Mathieu
Mathieu

Reputation: 316

read double value from a file: std::invalid_argument after std::stod call

#include <iostream> 
#include <fstream>
#include <sstream>


int main() {

    std::ifstream file("data.txt");
    std::string   line, numStr;

    // read first line
    std::getline(file, line);
    
    // read first value of first line
    std::istringstream lineStream(line);
    std::getline(lineStream, numStr, '\t');

    std::cout << "numStr= " << numStr << std::endl; // prints "numStr = "0.0014
    double num = std::stod(numStr); // <-- this failes
}

enter image description here

The file data.txt contains only one line with two values (see above picture), separated by tab.

When I run the above program using g++, I get the output

numStr= 0.0014
terminate called after throwing an instance of 'std::invalid_argument'
  what():  stod
Aborted (core dumped)

As you can see, the string is printed properly but for whatever reason, numStr.length() = 9, which is wrong since the string has only six chars.

Any idea what goes wrong here?

UPDATE: After debugging, I figured out the file contains a BOM character at the beginning causing the issue. After re-saving without BOM, the code works as expected.

Upvotes: 1

Views: 90

Answers (1)

Prachi
Prachi

Reputation: 1

1.Trim whitspace- ensure numStr doesn't contain any leading space 2. Handle Errors- add exception handling to catch invalid strings

Upvotes: -5

Related Questions