c++ - 在不使用内置函数(如 atoi 或 atof)的情况下将字符串转换为浮点数或整数
问题描述
我是 C++ 新手,我们的老师要求我们获得一个完成上述标题的函数。到目前为止,我有一个将字符串转换为整数的函数,但是如果字符串中的数字代表浮点数,我不知道如何修改它以使其工作。
int convert(char str[], int size) {
int number = 0;
for (int i = 0; i < size; ++i) {
number += (str[i] - 48)*pow(10, (size - i - 1));
}
return number;
}
如果我运行:
char myString[] = "12345";
convert(myString, 5);
我得到:
12345
但是如果我运行:
char myString[] = "123.45";
convert(myString, 5);
我得到:
122845
我怎样才能修改我的程序以使用浮点数?我知道convert函数是为了返回一个 int ,所以我应该再使用两个函数吗?
我在考虑一个确定字符串是否被转换为整数或字符串的方法,而另一个实际上将字符串转换为浮点数的方法。
解决方案
这是这样做的功能...
template<class T, class S>
T convert_string_to_number(S s)
{
auto result = T(0.l);
if (s.back() == L'F' || s.back() == L'f')
s = s.substr(0u, s.size() - 1u);
auto temp = s;
auto should_add = false;
if (!std::is_floating_point<T>::value)
{
should_add = temp.at(temp.find_first_of(L'.') + 1) >= '5';
temp.erase(temp.begin() + temp.find_first_of(L'.'), temp.end());
}
else if (temp.find_first_of(L'.') != S::npos)
temp.erase(temp.begin() + temp.find_first_of(L'.'));
for (int i = temp.size() - 1u; i >= 0; --i)
if (temp[i] >= L'0' && temp[i] <= L'9')
result += T(std::powl(10.l, temp.size() - i - 1.l) * (temp[i] - L'0'));
else
throw std::invalid_argument("Invalid numerical string!");
if (s.find(L'-') != S::npos)
result = -T(std::fabs(result));
if (s.find(L'.') != S::npos && std::is_floating_point<T>::value)
result /= T(std::powl(10.l, s.size() - s.find(L'.') - 1.l));
return std::is_floating_point<T>::value ? T(result) : T(result + T(should_add));
}
像往常一样使用它...
auto some_number = convert_string_to_number<float>(myString);
...