我是 C++ 的新手,我们的老师要求我们获得一个执行上述标题的函数。到目前为止,我已经有了一个将字符串转换为整数的函数,但我不知道如何修改它以使其在字符串中的数字表示 float 时起作用。 p>
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
如何修改我的程序以使其也能使用 float ?我知道 convert 函数是为了返回一个 int,所以我应该再使用两个函数吗?
我在考虑一个确定字符串是要转换为整数还是字符串,另一个实际将字符串转换为 float 。
最佳答案
这是这样做的功能......
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);
...
关于c++ - 不使用内置函数(如 atoi 或 atof)将字符串转换为 float 或整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52705166/