从包含单词的文件中提取double
Extract double from file with words
我知道这可能是一项简单的任务,在阅读其他问题的答案时,我发现这段代码应该能完成
#include<fstream>
#include<iostream>
#include<iomanip>
#include<string>
using namespace std;
int main() {
const char* filename = "integral_wh.out";
std::ifstream inFile(filename);
// Make sure the file stream is good
if(!inFile) {
cout << endl << "Failed to open file " << filename;
return 1;
}
double n;
string word;
while(inFile >> word >> n){
cout << word;
cout << n;
}
return 0;
}
我正在读取的文本文件是
Integral, Sample: Z/W + jets - ntp_Alpgen_Ztt.root 3.33645 +- 0.31588
Integral, Sample: Z/W + jets1 - ntp_Alpgen_Zmm.root 2.52853 +- 0.34243
Integral, Sample: Z/W + jets2 - ntp_Alpgen_Zee.root 7.97980 +- 0.70667
Integral, Sample: Z/W + jets3 - ntp_Wj_0.root 0.00000 +- 0.00000
Integral, Sample: Z/W + jets4 - ntp_Wj_1.root 0.67329 +- 0.48556
Integral, Sample: Z/W + jets5 - ntp_Wj_2.root 1.44122 +- 0.89388
当我运行程序时,它不能读取double,它不会cout
任何内容。我也试过
while(inFile >> n){
cout << n;
}
并且不输出任何内容。我想获得的是使用它们进行操作的单个数字,也许可以将它们保存为成对的数字,比如
pair<double,double> alpgen = make_pair(3.33645,0.31588);
或者类似的东西。
对于标准流,运算符(operator>>
)中的流使用空格来分隔令牌-在这种情况下,您的读取操作将失败,因为它将读取一个字符串(Integral,
),然后下一个令牌(Sample:
)将尝试解析为双符-这将失败。
您需要消耗所有的字符串令牌,然后是double等。
读取整行,在空白处拆分为一个向量,并获取向量的最后一项和倒数第三项如何?
相关文章:
- 从包含m行的文件中提取n行,必要时(惰性地)重复该文件
- 如何从 std::atomic 中提取指针 T<T>?
- 为什么istream不支持右值提取
- 如何设置一个范围来提取我想要获得的信息
- C++在数学计算中将double转换为int
- 在c++中为double类型的数组创建一个unique_ptr
- 视觉工作室项目.提取源文件夹名称
- C++17 - 使用自定义分配器的节点提取/重新插入 - 适用于 clang++/libc++,但不适用于 libstd
- vector<vector<double>> to mxArray using memcpy
- (double) 和 double() 之间的区别
- 从字符串中提取整数并形成一个数组
- C++标准是否允许<double>在没有开销的情况下实现 std::可选
- C ++中的StringStream有助于使用向量从字符串中提取逗号分隔的整数,而不是空格分隔的整数,为什么?
- asn1c 不会从 asn.1 模块中提取八位字节字符串的默认值
- 从 std::vector<无符号字符>切片中提取 int?
- 在C++中使用重载提取运算符时出现问题
- 在 Qt(C++) 中使用 QProcess 解压缩 - 提取目录问题
- C++(.cpp文件和.h文件)拆分代码并添加一个函数,提取 - 这很容易吗?
- 从包含单词的文件中提取double
- 从内存中提取double的字节值