C++ 将字符串数组中的字符转换为浮点
我正在做一个项目,它接受坐标用户的字符串输入。 输入示例:C++ 将字符串数组中的字符转换为浮点,c++,string,casting,char,C++,String,Casting,Char,我正在做一个项目,它接受坐标用户的字符串输入。 输入示例: "Polygons = [(1, 1), (4, 1), (4, 5), (3,5), (1, 5); (5,3), (3, 4), (6, 4), (6, 12), (3, 12)]" 我正在做的一个函数是检查最小/最大X,它显然是a之后的任何数字,但是困扰我的问题是将a之后的数字转换为浮点,以便在计算和数字比较中使用它 #include <iostream> #include "string"
"Polygons = [(1, 1), (4, 1), (4, 5), (3,5), (1, 5); (5,3), (3, 4), (6, 4), (6, 12), (3, 12)]"
我正在做的一个函数是检查最小/最大X,它显然是a之后的任何数字,但是困扰我的问题是将a之后的数字转换为浮点,以便在计算和数字比较中使用它
#include <iostream>
#include "string"
#include <stdlib.h>
#include <cstdlib>
using namespace std;
//Using a constant string for testing
string Polygon_Input = "Polygons = [(1, 1), (4, 1), (4, 5), (3,5), (1, 5); (5,3), (3, 4), (6, 4), (6, 12), (3, 12)]";
string Operation;
float Min_X = 9999;
int main()
{
getline(cin, Operation);
if (Operation == "Minimum_X")
{
for (int i; i <= Polygon_Input.length(); i++)
{
if (Polygon_Input[i] == '(')
{
float X = Polygon_Input[i + 1];
if (X < Min_X)
{
Min_X = X;
}
}
}
cout << Min_X;
}
这不起作用,它总是以Min_X的形式输出49
我也尝试过同样的代码,只做了一次修改,但仍然不起作用
if (Polygon_Input[i] == '(')
{
string X_As_String = Polygon_Input.substr(i + 1, i + 1);
float X = atof(X_As_String.c_str());
if (X < Min_X)
{
Min_X = X;
}
首先,代码中有几个问题 浮动最小值X=9999 最小值必须在列表中。将第一个元素初始化为最小值,并将其与其余元素进行比较 如果X
对于int i=0;i由于所有x都大于0,并且您将Min_x初始化为0,因此您的x
//#include <limits> // no need for this
#include <iostream>
#include <string>
#include <cstdlib>
#include <cstdlib>
using namespace std;
//Using a constant string for testing
string Polygon_Input = "Polygons = [(1, 1), (4, 1), (4, 5), (3,5), (1, 5); (5,3), (3, 4), (6, 4), (6, 12), (3, 12)]";
string Operation("Minimum_X");
//float Min_X = 9999; ?????? Why
float Min_X;
bool flag(true);
int main()
{
//getline(cin, Operation); // commented out for test
if (Operation == "Minimum_X")
{
for (int i=0; i < Polygon_Input.size(); i++)
{
if ( Polygon_Input[i] == '(' )
{
// extract X values (i.e. the first co-ordinate of a point )
std::string temp = Polygon_Input.substr(i+1, Polygon_Input.find_first_of(",",i)-i-1 );
// convert strig to float
float X = std::stof(temp);
// store first element and compare it with the rest
if(flag){
Min_X = X;
flag=false;
}
// int X = Polygon_Input[i + 1] - '0'; ????? What is this?
if (X < Min_X)
{
Min_X = X;
}
}
}
cout << Min_X << endl;
}
return 0;
}