I am new to C++, and am doing a physics project with it.
There is a problem that I've run into:
I have made a Photon
class that has a member var called energy
(float).
In a loop (which parses a txt file of values), when ever I create a new Photon
, I assign it a certain energy
(as a string - which I later convert to float) through a constructor.
Then I push the photon
into the a Photon vector. When I cout
the energies right after Photon
creation, they are as expected, and correspond correctly to txt file.
But, immediately after the loop when I loop again through the vector of Photons, and print photons[i].energy
, the values are weirdly changed - some of them even NaN
!
void Event::addPhoton(string data) {
Photon p(data); // the string data is parsed in constructor
cout << "the energy: " << p.energy << " \n"; // energies output here are correct
photons.push_back(p);
// BUG somewhere here
cout << "Update: Just added a photon. Current photon energies: ***" << endl;
for (int i = 0; i < photons.size(); i++) {
cout << photons[i].energy << ", "; // here, values have changed !!
}
cout << endl;
}
Any ideas?
Update - Photon class:
#include <stdlib.h>
#include "Photon.h"
Photon::Photon() {
}
Photon::Photon(const Photon& orig) {
}
Photon::~Photon() {
}
Photon::Photon(string data) {
setData(data);
std::cout << "Set photon energy to " << energy << std::endl;
}
//parse momentum, energy values .. from data string
void Photon::setData(string data) {
std::cout << "datastring" << data << std::endl;
string delimiter = " ";
size_t pos = 0;
string token;
vector<string> values;
size_t numDels = std::count(data.begin(), data.end(), ' ');
///while ((pos = data.find(delimiter)) != string::npos ) {
for (int i = 0; i < numDels+1; i++) {
pos = data.find(delimiter);
token = data.substr(0, pos);
values.push_back(token);
data.erase(0, pos + delimiter.length());
}
momentum = Momentum(atof(values[0].c_str()), atof(values[1].c_str()), atof(values[2].c_str()));
energy = atof(values[3].c_str());
}
float Photon::getEnergy() {
return energy;
}