Joe
Joe

Reputation: 1

Help with conversion string to double?

I don't know what's going on here. I am converting two strings to doubles and the first one always goes through, but the second doesn't and it doesn't matter which way I switch them! Here's the code:


    #include <iostream>
    #include <math.h>
    #include <string>
    #include <sstream>
    using namespace std;

    int main() {
        string temp;
        double ax,bx,cx,ay,by,cy;
        cout << "Enter x and y for point 1 (separated by a comma)";
        cin >> temp;
        int where=temp.find(",");
        int hmm=temp.length()-where;
        cout << hmm << endl << where << endl;
        cin.get();
        stringstream ss;
        string stAx,stAy;
        stAx= (temp.substr(0,where));stAy =  (temp.substr(where+1, hmm-1));
        ss << stAx;ss >> ax;
        ss << stAy;ss >> ay;
        cout << "Ax: " << ax << endl;
        cout << "Ay: " << ay << endl;

        system("pause");
        return 0;   
    }


 

Can anybody figure out what I'm doing wrong?

Thanks in advance!

Upvotes: 0

Views: 242

Answers (3)

Nim
Nim

Reputation: 33645

erm, I'm sure your problem is fixed, what I don't understand is why you can't simply do:

  double dx, dy;
  cout << "enter x and y co-ordinates (separated by a space): " << endl;
  cin >> dx >> dy;

  cout << "dx: [" << dx << "], dy:[" << dy << "]" << endl;

Upvotes: 0

Loki Astari
Loki Astari

Reputation: 264649

The simplist way is to use boost::lexical_cast.

If boost is not available then you can write your own (not as good as boost version which can cast to string and does error checking. But goo enough for simple programs).

#include <sstream>
#include <iostream>

template<typename T>
inline T MyCast(std::string const & value)
{
    std::stringstream  ssinput(value);

    T  result;
    ssinput >> result;

    return result;
}

int main()
{
    double x = MyCast<double>("12.345");
    std::cout << x;
}

Upvotes: 1

Grammin
Grammin

Reputation: 12215

Your problem is that you are using the same string stream for both ax and ay. You need ssA, and ssY. Or try ss.flush()

Upvotes: 3

Related Questions