CKM
CKM

Reputation: 1971

Invalid argument error with stod

I'm getting the terminate called after throwing an instance of 'std::invalid_argument for stod function for the following lines of code:

#include <iostream>
#include <string>
#include <sstream>

int main() {
    std::string line = "5,,1,1,1";

    std::stringstream lineStream(line);
    std::string cell;
    std::string::size_type sz;

    while (std::getline(lineStream, cell, ','))
    {
       std::cout << std::stod(cell, &sz) << std::endl;
    }
}

Can somebody point me out the reasons for the exact error?

Thanks in advance.

EDIT: I noticed that error is because of the space " " between two commas "," in the line. Now the question is: Does getline return space in the cell variable?

Upvotes: 1

Views: 15518

Answers (1)

NathanOliver
NathanOliver

Reputation: 180630

The issue here is you have an empty cell. There is no conversion from empty to a valid double so stod throws an excpetion. What you need to do is skip empty cells like

while(std::getline(lineStream, cell, ','))
{
    if (!cell.empty())
        cout<<stod(cell, &sz)<<endl;
}

Upvotes: 4

Related Questions