我知道这可能是一项简单的任务,我发现,阅读其他问题的答案,这段代码应该可以解决这个问题
#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);
或类似的东西。
答案 0 :(得分:0)
对于标准流,运算符(operator>>
)中的流使用空格来分隔标记 - 在这种情况下,您的读取操作将失败,因为它将读取一个字符串(Integral,
),然后{1}}下一个令牌(Sample:
)将尝试被解析成双重 - 这将失败。
你需要消耗所有的字符串标记,然后是双重等等。
答案 1 :(得分:0)
如何读取整行,在空白处分割成一个向量,并获取向量的最后一个和第三个到最后一个项?