C++ – How to use std::stod properly

c

I am working on writing a simple linear line calculator. For example, a user can enter two equations (strings) such as y=5x+3 and y=-3x+6. The most basic feature of this calculator is that it will return the intersection point of these two lines.

The obstacle I can't seem to figure out is how to parse the string into two pieces of data: the slope, and the y-intercept. This is a simple calculator, so the format of both lines will be y=mx+b, however, both the slope and/or y-intercept may be non-integer numbers (i.e. floats).

I came across a function in the string library called stod, which converts a number in a string to a numerical value (am I understanding this correctly?).

http://www.cplusplus.com/reference/string/stod/

My question is, will this function do the job? If so, how exactly do I use the "idx" parameter? I don't quite understand it.

If this isn't going to work, how can I parse this user-entered data?

  • both equations are strings (y=mx+b)
  • m and b have private variables dedicated in storing the decimal value (i.e. double m_ and double b_ are private member variables)

Best Answer

This is how the idx parameter works:

#include <string>
#include <iostream>

int main(void)
{
    std::string data = "y=5.9568x+3.14"; //say you have a string like this..

    double y, x, m, b;
    y = 0;
    x = 0;

    std::size_t offset = 0; //offset will be set to the length of characters of the "value" - 1.
    m = std::stod(&data[2], &offset); //So we want to get the value "5.9568
    b = std::stod(&data[offset + 3]); //When we reach this line, offset has a value of 6

    std::cout<<b;
    return 0;
}

So now you're asking why does it have a value of 6? Well because:

5.9568 is exactly: 6 characters in length. Thus on the next line when we do

b = std::stod(&data[offset + 3]);

we are actually feeding it a pointer to address of x + 3.. and that turns out to be right at the beginning of the 3.14.

In other words it's equivalent to:

std::stod(&data[9]);

So that idx parameter is actually the index/length of the double in characters within the string. If the string is:

str = "3.14159"

Then std::stod(str, &idx) will make idx equal to: 6.

if the string is:

str = "y = 1024.789" then std::stod(&str[4], &idx) will make idx equal to: 8 STARTING FROM &str[4]..