从 istream 获取下一个浮点数?
STL 中是否存在可以从文件中获取下一个浮点数的函数?
例如:
Data.txt:
blah blah blah blah blah
blah blah blah blah blah
blah 0.94 blah blah blah
std::istream inputFile(Data.txt);
float myNumber = inputFile.GetNextFloat();
std::cout << myNumber << std::endl; // Prints "0.94"
Does there exist a function in the STL that will get the next float from a file?
e.g.:
Data.txt:
blah blah blah blah blah
blah blah blah blah blah
blah 0.94 blah blah blah
std::istream inputFile(Data.txt);
float myNumber = inputFile.GetNextFloat();
std::cout << myNumber << std::endl; // Prints "0.94"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
C++ 中的 I/O 流函数(以及 C 中的 stdio 函数)旨在读取格式化输入。也就是说,它们适合读取程序期望类型的值。没有任何东西会尝试从流中读取值并且只接受特定类型,而丢弃其他值。此外,还不清楚什么是“浮点数”:例如,“+1”对于某些人来说是一个完美的“浮点数”,而其他人可能希望它至少包含一个小数点,甚至可能在后面至少包含一位数字小数点。
C++2011 和 Boost(如果您无权访问 C++2011 实现)实现正则表达式,您应该能够使用它检测与您的首选定义匹配的下一个浮点数。这是该技术的一个简单演示:
The I/O stream functions in C++ (and likewise the stdio functions in C) are designed to read formatted input. That is, they are tailored to reading values of types expected by the program. There is nothing which tries to read values from a stream and only accept a specific type, discarding other values. Also, it is somewhat unclear what a "float" might be: for example, "+1" is a perfectly good "float" for some while others might want it to contain at least a decimal point, possibly even at least one digit after the decimal point.
C++2011 and Boost (if you don't have access to a C++2011 implementation) implement regular expressions and you should be able to detect the next floating point number matching your preferred definition using this. Here is a simple demo of this technique: