为什么用atof将string类型3001转换为float类型结果为0要如何正确转换
使用atof将string类型的3.001转换为float类型结果为0的原因是atof函数只能处理以空格、制表符或换行符结尾的字符串。而3.001后面没有这些字符,所以atof无法正确解析。
要正确转换,可以使用其他方法,例如std::stof函数:
#include <iostream>
#include <string>
int main() {
std::string str = "3.001";
float f = std::stof(str);
std::cout << f << std::endl;
return 0;
}
输出结果为3.001。
原文地址: http://www.cveoy.top/t/topic/iq0x 著作权归作者所有。请勿转载和采集!