infile -> outfile does nothing

I'm trying to ignore some lines in temp.txt and copy the rest to temp2.txt.
when the line has two doubles they should be output, otherwise ignored.

1
2
3
4
5
6
7
8
9
10
11
    infile.open("temp.txt");
    outfile.open("temp2.txt");
    double mass, intensity;
    while (infile)
    {
        if (infile >> mass >> intensity)
            outfile << mass << " " << intensity << endl;
        else
            infile.ignore();
    }
    return 0;


content of temp.txt is:
1
2
3
4
5
6
7
8
9
1tart	
10.00
Zoom
1nd	140.00

Cycle	CycleDate	CycleTime	
1	12/22/2017	12:51:09
1M:89
ScanData	1

Not this data but the data below should be in temp2.txt
1
2
3
4
5
6
7
20.00	963.402

20.03	947.382

20.06	918.017

20.09	898.037


temp2.txt is empty.


I noticed after copy pasting from temp.txt the layout changes.
This is the layout as in the textfile https://imgur.com/a/BQw9b , whereas above is after copy pasting.

What's going wrong here?

Last edited on
I'm not really sure what is going on in your code, but I would take a different approach.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const unsigned int max_size = 100; //or whatever value you like
char * buffer[max_size];
std::string massString, intensityString;

while(infile.getline(buffer, max_size) ) {
     
     split(buffer,massString,intesityString); //you need to implement this

     if( checkDouble(massString) && checkDouble(intensityString) ) { //need to implement this function as well
  
        outfile<<massString<<" "<<intensityString<<std::endl;

     }

}


To create split simply iterate through buffer and as soon as you find a blank space you separate the buffer into 2. Then trim every space and check that the second string does not contain blank spaces.
If you can't do this (line does not contain 2 elements) return 2 empty strings.

To create checkDouble look though every character and check if it is a digit or not, moreover after finding a dot no other dot should be found.
When infile enters an error state, you must call clear to clear the error state. Then, you probably want to discard the entire line and not just a single character. Also, this is one of those situations where you probably do want to loop on eof, if this is the way you're going to do things:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <fstream>

int main() {
  std::ifstream infile("temp.txt");
  std::ofstream outfile("temp2.txt");

  double mass, intensity;
  // This is one of those times where eof is appropriate:
  while (!infile.eof()) {
    if (infile >> mass >> intensity) 
      outfile << mass << ' ' << intensity << '\n';
    else {
      infile.clear();
      infile.ignore(1000, '\n');
    }
  }
}


I think you'll find you have a thing or two more to iron out before it works quite the way you want, though.
@cire

Thank you, this works as I need it to. What is the difference between infile and !infile.eof()?
Registered users can post here. Sign in or register to post.