我不知道这里发生了什么。我正在将两个字符串转换为双字符串,第一个字符串总是通过,但第二个字符串没有,并且我切换它们的方式无关紧要! 这是代码:
#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;
}
有人可以弄清楚我做错了什么吗?
提前致谢!
答案 0 :(得分:3)
您的问题是您对ax和ay使用相同的字符串流。你需要ssA和ssY。或者尝试ss.flush()
答案 1 :(得分:1)
简单的方法是使用boost :: lexical_cast。
如果没有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;
}
答案 2 :(得分: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;