2010-12-22 66 views
0

我不知道这里发生了什么事。我将两个字符串转换为双精度值,第一个字符串总是经过,但第二个字符串没有,并且切换它们的方式并不重要! 下面的代码:帮助转换字符串加倍?


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


任何人都可以找出我做错了吗?

在此先感谢!

+1

看来你的代码的一部分丢失,所以我有猜测你的问题是什么。但你有没有看过boost :: lexical_cast()呢? – Axel 2010-12-22 19:09:32

回答

3

你的问题是你对ax和ay都使用相同的字符串流。你需要ssA和ssY。或者试试ss.flush()

+0

对不起,不具体。我想要做的是接收一个由逗号分隔的2个数字的字符串,然后通过使用string :: substr将它们分成2个数字(双精度)。我知道,我的代码有点混乱。 主要问题在于我使用stringstream的部分地方。 \t ss << stAx;ss >> ax; \t ss << stAy;ss >> ay; 这应该通过stringstream将字符串stAx转换为双斧头,并且工作正常,但stAy和ay部分不起作用 – Joe 2010-12-22 19:19:14

1

简单的方法是使用boost :: lexical_cast。

如果boost不可用,那么你可以编写自己的(不如可以转换为字符串并进行错误检查的boost版本,但对简单程序来说足够了)。

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

呃,我敢肯定,你的问题是固定的,我不明白的是为什么你不能简单地做:

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

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