string转化为float的问题

gouyingqi 2009-11-03 08:31:28
如题,我想将string转化为float,我用的是float f=atof(str);

然后报错如下
error C2664: 'atof' : cannot convert parameter 1 from 'class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >' to 'const char *'
No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

请教错在哪里?怎么解决?不一定要用string,只要输入一个字符串再转换成浮点数就行;

还有我想要小数点后达到7位,float是不是不够?
...全文
259 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
gouyingqi 2009-11-03
  • 打赏
  • 举报
回复
哦,我知道了,谢谢各位
gouyingqi 2009-11-03
  • 打赏
  • 举报
回复
double d=str.c_str();
还是不行啊。。。
昵称很不好取 2009-11-03
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 gouyingqi 的回复:]
哦,谢谢,那我想要转化后的小数点后面达到7位,float行不行?
[/Quote]
float精度只有6位
quintard 2009-11-03
  • 打赏
  • 举报
回复
楼上
昵称很不好取 2009-11-03
  • 打赏
  • 举报
回复
int main() 
{
string s = "123";
float f = atof(s.c_str());
cout<<f<<endl;

return 0;
}
失落的凡凡 2009-11-03
  • 打赏
  • 举报
回复
用double 吧
失落的凡凡 2009-11-03
  • 打赏
  • 举报
回复
atoi只能接受C风格字符串,也就是char str[20]这种格式的,string是一个类,atoi不支持的
gouyingqi 2009-11-03
  • 打赏
  • 举报
回复
哦,谢谢,那我想要转化后的小数点后面达到7位,float行不行?
失落的凡凡 2009-11-03
  • 打赏
  • 举报
回复
atoi应该用str.c_str()

64,654

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧