编辑:
改为使用 atof
,因为在这种情况下它不会生成拷贝。从两个实现来看,它应该在第一个无效符号后停止。
原文:
考虑这个简单的设置:
const char* string = "1.0 2.0 3.0 4.0";
float float1 = stof(string);
float float2 = stof(string + 4);
float float3 = stof(string + 8);
在这种情况下,会一直解析到结束还是在初始位置后的第一个空白处停止?
我需要解析一个很长的浮点列表编码成一个字符串,所以我基本上需要知道我是否必须将数字复制到一个单独的(小)缓冲区并在这个缓冲区上调用 stof,或者我可以使用 stof 作为以上。
最佳答案
它丢弃前导空格并解析整个字符串。摘自std::stof引用(强调我的):
Function discards any whitespace characters (as determined by std::isspace()) until first non-whitespace character is found. Then it takes as many characters as possible to form a valid floating-point representation and converts them to a floating-point value.
在您使用 string + 4
和 string + 8
表达式的情况下,您提供了 "2.0 3.0 4.0"
和 "3.0 4.0"
字符串到函数。您还应该避免将变量命名为 string
。
关于c++ - std::stof 是解析整个字符串还是在第一个空格/换行符处停止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48629948/