从包含单词的文件中提取double

Extract double from file with words

本文关键字:提取 double 文件 包含单      更新时间:2023-10-16

我知道这可能是一项简单的任务,在阅读其他问题的答案时,我发现这段代码应该能完成

#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等。

读取整行,在空白处拆分为一个向量,并获取向量的最后一项和倒数第三项如何?