Extraer el doble del archivo con palabras

I know that this might be an easy task and i found, reading the answer to other questions, that this code should do the trick


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;

The text file I'm reading from is

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

when I run the program it can't read the double, it doesn't cout anything. I tried also with

   while(inFile >> n){

        cout << n;

and doesn't output anything. What i would like to obtain is the single numbers to use them for operations, maybe saving them into pairs, like

pair<double,double> alpgen = make_pair(3.33645,0.31588);

o algo así.

preguntado el 02 de febrero de 12 a las 10:02

2 Respuestas

For a standard stream, the stream in operator (operator>>) uses a space to delimit tokens - in this case, your read operation will fail because it will read one string (Integral,), then the next token (Sample:) will attempt to be parsed into a double - which will fail.

You need to consume all the string tokens, then the double etc.

Respondido 02 Feb 12, 14:02

Oh that explains why it doesn't do what I'm expecting! I try to cycle over strings to consume the all before reading the double! - drkg4b

How about reading the whole line, splitting into a vector on whitespace, and get the last and third to last items of the vector?

Respondido 02 Feb 12, 14:02

Yes this might work, I thought of the simplest thing to try and wondering why it isn't working. - drkg4b

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.