c++ - 将字符数组转换为 float

标签 c++ visual-c++ floating-point

我正在尝试将我的字符数组数据转换为 float 。可能吗?

代码:

char str[5] = {'1', '2', '.', '3'}
void main(char str[])
{
    float var = (float)str[]; //error
}

此代码无效。所以我也尝试使用:

float var = (float) (str[0], str[1], str[2], str[3]); //output: 49

还有

float var = (float) (str[0] + str[1] + str[2] + str[3]); //output: 196

但它们也没有按预期工作..

我的预期输出应该是 float var = 12.3

最佳答案

是的,使用 std::stof ,它接受一个 C 字符串(即一个以 null 结尾的字符数组)并给你一个 float (如果可能的话):

#include <iostream>
#include <string>
#include <cassert>

int main(int argc, char* argv[])
{
   assert(argc >= 2);
   const float var = std::stof(argv[1]);
   std::cout << var << '\n';
}

// $ myProgram 12.3
// 12.3

( live demo )

请注意,我还更正了您的 main 返回类型(必须是 int),并且我使用了一组更常规的函数参数:虽然他们的要求取决于实现,VS doesn't document any support for this unconventional variant .

当然,您不需要来自命令行的输入:

#include <iostream>
#include <string>

int main()
{
   const std::string str = "12.3";
   // or `const std::string str   = {'1', '2', '.', '3'};
   // or `const char        str[] = {'1', '2', '.', '3', '\0'};

   const float var = std::stof(str);
   std::cout << var << '\n';
}

// $ myProgram
// 12.3

( live demo )

关于c++ - 将字符数组转换为 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24529770/

相关文章:

java - 为什么 0.1 正确地表示为 float ? (我知道为什么不是 2.0-1.9 的结果)

c++ - 如何从外部应用程序读取使用 FireFox 下载的文件的源 URL?

c++ - 从文字字符串生成编译时常量整数

c++ - 在 C++ 中说 "promote everything to floating before calculation"的确定性方式

c++ - SDKDDKVer.h 是做什么用的?

c++ - 如何在 VC++ 中获取 WPF 应用程序的屏幕截图?

javascript - ASP.NET MVC : Get javascript floating point number into hidden input

c++ - 如何定义两个依赖类?

c++ - 编译器的优化范围是什么?

c++ - 使用另一个模板类链接一个模板类(错误 LNK2001)