0

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!

1
  • 1
    Seems part of your code is missing, so I have to guess what your problem is. But have you looked at boost::lexical_cast() yet? Commented Dec 22, 2010 at 19:09

3 Answers 3

3

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()

Sign up to request clarification or add additional context in comments.

3 Comments

Sorry for not being specific. What I am trying to do is receive a string with 2 numbers separated by a comma, then separate them into 2 numbers (doubles) by using string::substr. My code is a little jumbled up, I know. The main problem was in part where I used stringstreams. ss << stAx;ss >> ax; ss << stAy;ss >> ay; This was supposed to convert string stAx to double ax via the stringstream, and that worked, but the part with stAy and ay didn't work
ss.flush() didn't fix the problem on my machine. ss.clear() did. I'd recommend ssX and ssY anyway, but if not, `ss.clear() will work.
Thanks! it works! I didn't know that you had to clear stringstreams.
1

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;
}

Comments

0

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;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.