以下程序在std::stringstream
使用.double
std::numeric_limits<double>::infinity
#include <string>
#include <sstream>
#include <iostream>
#include <limits>
#include <iterator>
int main() {
std::stringstream stream;
double d;
// Part 1
d=4;
stream << d << " ";
d=std::numeric_limits<double>::infinity();
stream << d << " ";
d=5;
stream << d;
stream.seekg(std::ios_base::beg);
std::string s = stream.str();
std::cout << "string : " << s << std::endl;
// Part 2
std::cout << "Extraction of data 1:" << std::endl;
stream.seekp(std::ios_base::beg);
stream >> d;
std::cout << d << std::endl;
stream >> d;
std::cout << d << std::endl;
stream >> d;
std::cout << d << std::endl;
// Part 3
std::cout << "Extraction of data 2:" << std::endl;
std::istringstream stream2(s);
std::istream_iterator<double> iter(stream2);
std::istream_iterator<double> eos;
while (iter != eos)
{
std::cout << (*iter) << std::endl;
iter++;
}
return 0;
}
现场观看。
输出是
string : 4 inf 5
Extraction of data 1:
4
0
0
Extraction of data 2:
4
在第 1 部分中,将double
“无穷大”写入 astringstream
并string
从中提取出对应于这种无穷大的“inf”。
然而,在第 2 部分中,子字符串“inf”显然被提取为 0。此外,流似乎处于错误状态,因为连续提取再次给出 0。
类似地,在第 3 部分中,aistream_iterator
用于double
从字符串中提取 s。迭代器在读取“inf”之前到达流的末尾。
double
显然,通过提取单词而不是将它们中的每一个转换为“正常”双精度词或std::numeric_limits<double>::infinity
遇到“inf”时,可以轻松解决问题。然而,这似乎是在重新发明轮子,因为标准库已经包含大量用于从流中提取数据的代码......
- 为什么插入和提取 a 时会有区别
std::numeric_limits<double>::infinity
? - 在标准库中,是否有可能提取
double
也可能是无穷大的 a,而无需编写提取单词并将其转换为 double 的函数?
附加说明
根据 c++ 参考,std::stod和类似函数已经将“inf”转换为无限表达式。因此,看起来std::stringstream::operator<<
不使用std::stod
或类似将一段字符串转换为double
.