【问题标题】:How convert variable string [] to float [closed]如何将变量字符串 [] 转换为浮点数 [关闭]
【发布时间】:2018-08-07 07:53:33
【问题描述】:

如何将字符串转换为浮点数?

这是我的代码:

string A[3] = {"20","21"};
float convertA ;

convertA = atof (A[1]) ;
cout << convertA << endl ;

这就是显示的内容:

-1 #lND

关于我可能做错的任何建议?

【问题讨论】:

  • 它甚至可以编译吗?那些字符串是std::strings 吗?
  • 这不会编译。你想要:convertA = atof(A[1].c_str());,除非string 不是std::string;我不能只用 4 行代码来判断。
  • std::string 变量上使用std::stofatof 用于 C 字符串,即 const char *
  • 输出仍在发出-1。 #IND
  • 这不是您的完整代码。请发帖minimal reproducible example

标签: c++ visual-c++ visual-studio-2012


【解决方案1】:

阅读atof()的手册页,convertA的类型应该是double

double atof (const char* str);

convertA = atof (A[1]) ; /* it won't work */

应该是

convertA = atof(A[1].c_str());

工作代码

#include<iostream>
#include<stdlib.h>
int main() {
        std::string A[3] = {"20","21"};
        double convertA ;

        //convertA = atof (A[1]) ;
        convertA = atof(A[1].c_str());
        std::cout << convertA << std::endl ;

        return 0;
}

编辑: 要将字符串转换为浮点数,您可以使用stof() 而不是atof()。在这里找到更多信息http://www.cplusplus.com/reference/string/stof/

【讨论】:

  • std::stof 可用。
  • 是的@super你是对的。
  • 输出仍然是-1。 #IND
  • @rafinsanovriardhira 编译我回答的代码,它会工作。
  • 数据=21 是真的,但是有一个变量-1.#IND
猜你喜欢
  • 2011-11-25
  • 1970-01-01
  • 1970-01-01
  • 2018-02-15
  • 2011-12-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多