C++ 如何把C风格字符串转化为数字

#include "stdafx.h"
#include<string> 

#include "iostream"


using namespace std;


double ToNumber(const char* charArray)
{
double Value = 0;
bool isNegative = false;
bool isFloat = false;
int floatCount = 0;

//处理首字母
if (*charArray == '-')
{
isNegative = true;
charArray++;
}
if (*charArray == '+')
{
charArray++;
}

while (*charArray) //*charArray != '\0'
{
int intChar = *charArray - '0';
if (*charArray == '.') {
isFloat = true;
charArray++;
continue;
}

if (isFloat) {
floatCount++;
Value = Value +intChar * pow(0.1, floatCount);
}
else {
Value = Value * 10+intChar;
}

charArray++;
}
if (isNegative)Value = -Value;
return Value;
}

bool InputIsLegue(char* input) {
if (*input == NULL) {
cout << "Error:输入不能为空。请重新输入!" << endl << endl;
return false;
}
int pointCount = 0;
//判断首字母
if (*input == '-' || *input == '+') {
input++;
}

while (*input != '\0')
{
if (*input > '9' || *input < '0')
{
if (*input != '.')
{
cout << "Error:输入数字字符串不能包含非数字字符。请重新输入!" << endl << endl;
return false;
}
else
{
pointCount++;
if (pointCount >= 2)
{
cout << "Error:输入数字字符串不能包含多个小数点。请重新输入!" << endl << endl;
return false;
}
}
}
input++;
}
cout << "输入合法,可转为数字..." << endl;
return true;
}
int main()
{
////测试用例
//const char* case0= "123095";
//const char* case1 = "56486759815872639127598247598275423894729374";
//const char* case3 = "78.54";
//const char* case33 ="78.54.48";
//const char* case4 = "-5673";
//const char* case5 = "+5673";
//const char* case6 ="56AAAAAA73";

int SIZE = 100;
char* input=new char(SIZE);

while (1) 
{
cin.getline(input, SIZE);
if (*input == 'q')break;

bool isLegue= InputIsLegue(input);
if (isLegue == false)continue;
else 
{
double result = ToNumber(input);
cout << "转换结果:"<<result << endl<<endl;
}
}
    return 0;
}













猜你喜欢

转载自blog.csdn.net/danteshenqu/article/details/79317354