【问题标题】:C++ converting string to double using atofC++ 使用 atof 将字符串转换为双精度
【发布时间】:2013-07-12 16:00:55
【问题描述】:

我无法让atof() 函数工作。我只希望用户输入值(以十进制数的形式),直到他们输入'|',然后它才能打破循环。我希望这些值最初作为字符串读入,然后转换为双精度值,因为我在过去使用这种输入方法时发现,如果输入数字“124”,它会跳出循环,因为“124”是'|' 的代码字符。

我环顾四周,发现atof() 函数显然将strings 转换为doubles,但是当我尝试转换时,我收到了消息

“不存在从 std::string 到 const char 的合适转换函数”。

我似乎无法理解为什么会这样。

void distance_vector(){

double total = 0.0;
double mean = 0.0;
string input = " ";
double conversion = 0.0;
vector <double> a;

while (cin >> input && input.compare("|") != 0 ){
conversion = atof(input);
a.push_back(conversion);
}

keep_window_open();
}

【问题讨论】:

标签: c++ string double atof


【解决方案1】:

你需要

atof(input.c_str());

这将是有问题的“合适的转换函数”。

std::string::c_strDocumentation:

const char* c_str() const;
获取等效的 C 字符串
返回一个指向数组的指针,该数组包含以 null 结尾的字符序列(即 C 字符串),表示字符串对象的当前值。

【讨论】:

    【解决方案2】:

    您还可以使用strtod 函数将字符串转换为双精度:

    std::string param;  // gets a value from somewhere
    double num = strtod(param.c_str(), NULL);
    

    您可以查看 strtod 的文档(例如,如果您使用的是 Linux / Unix,则为 man strtod)以查看有关此功能的更多详细信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-10
      • 2015-04-10
      • 1970-01-01
      • 2014-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-11
      相关资源
      最近更新 更多