C ++使用atof将字符串转换为double [英] C++ converting string to double using atof

查看:1218
本文介绍了C ++使用atof将字符串转换为double的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法使atof()函数工作。我只希望用户输入值(以十进制数的形式),直到它们输入'|',然后它断开循环。我想要的值最初是作为字符串读取,然后转换为双打,因为我发现在过去,当我使用这种方法的输入,如果你输入数字'124'它突破了循环,因为'124'是代码'|'char。

I cannot get the atof() function to work. I only want the user to input values (in the form of decimal numbers) until they enter '|' and it to then break out the loop. I want the values to initially be read in as strings and then converted to doubles because I found in the past when I used this method of input, if you input the number '124' it breaks out of the loop because '124' is the code for the '|' char.

我环顾四周,发现了一个atof()函数,它显然将字符串转换为双精度,但是当我尝试转换时,我得到的消息没有合适的转换函数std :: string to const char exists。

I looked around and found out about the atof() function which apparently converts strings to doubles, however when I try to convert I get the message "no suitable conversion function from std::string to const char exists". And I cannot seem to figure why this is.

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();
}


推荐答案



You need

atof(input.c_str());

这将是合适的转换函数。

That would be the "suitable conversion function" in question.

std :: string :: c_str 文件


const char * c_str()const;

获取C字符串对等

返回一个指向数组的指针,该数组包含一个以null结尾的字符序列(即,一个C字符串),表示字符串对象的当前值。 / p>

const char* c_str() const;
Get C string equivalent
Returns a pointer to an array that contains a null-terminated sequence of characters (i.e., a C-string) representing the current value of the string object.

这篇关于C ++使用atof将字符串转换为double的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆