简体   繁体   English

将字符数组转换为浮点型

[英]Converting character array to float

I'm trying to convert my character array data into float. 我正在尝试将字符数组数据转换为float。 Is it possible? 可能吗?

Code: 码:

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

This code didn't work. 此代码无效。 So I also tried using: 所以我也尝试使用:

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

and also 并且

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

But they also did not work as expected.. 但是它们也没有按预期工作。

My expected output should be float var = 12.3 我的预期输出应为float var = 12.3

Yes, using std::stof , which takes a C-string (ie a null-terminated character array) and gives you a float back (if possible): 是的,使用std::stof ,它接受一个C字符串(即一个以空字符结尾的字符数组)并给您一个浮点返回(如果可能):

#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 ) 现场演示

Note that I have also corrected your main return type (which must be int ), and I've gone with a more conventional set of function arguments: though their requirements are up to the implementation, VS doesn't document any support for this unconventional variant . 请注意,我还更正了您的main返回类型(必须为int ),并且使用了一组更常规的函数参数:尽管它们的要求取决于实现,但VS并未记录 对此非常规的 任何支持 。变体

Of course, you don't need the input to be from command line: 当然,您不需要输入来自命令行的内容:

#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 ) 现场演示

std::string str = {'1', '2', '.', '3'};
float var = std::stof(str);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM