【问题标题】:Cannot convert a numerical string from a string array into a float [duplicate]无法将字符串数组中的数字字符串转换为浮点数[重复]
【发布时间】:2015-11-19 17:01:13
【问题描述】:

我正在尝试将包含字符串的数组转换为浮点数。索引 [j][2] 处的每个字符串都是一个必须转换为浮点数的数字。 i 是一个 int,其中包含数组的“行”总数。首先,我需要将它乘以 8,然后除以 10,然后将其转换为字符串并将其存储回数组中。我想稍后再将其转换为浮点数,但我需要记录每个浮点数属于哪个索引。所以我需要一种将字符串转换为浮点数的可靠方法。以下失败并给我这个错误消息:

for (int j = 0; j < i; j++) {
    float wow = strtof(array[j][2]);
    array[j][3] = (wow + float(i/10)*8);
}

错误:

无法将参数“1”转换为“std::string {aka std::basic_string}”到“const char*”到“float strtof(const char*, char**)”

strtof 的变体,如 stofatof 给我同样的错误。

【问题讨论】:

标签: c++ string type-conversion


【解决方案1】:

您使用了错误的功能。要将std::string 转换为float,您需要使用std::stof 而不是strtof

注意:std::stof 需要 C++11 或更高版本。如果没有,可以使用atof,但需要使用c_str()

【讨论】:

  • 我没有 C++11。但是,当我使用float wow = strtof(array[j][2].c_str()) 时,它说参数太少。
  • @Reginsmal 我的回答有误。如果你没有 C++11,你应该使用atoffloat wow = atof(array[j][2].c_str())
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-11-25
  • 2017-09-28
  • 1970-01-01
  • 2017-05-12
  • 1970-01-01
  • 2021-06-15
  • 1970-01-01
相关资源
最近更新 更多