Reputation: 16705
New Problem
boost::tokenizer<> token(line);
tokenizes decimal points! How can I stop this happening?
Previous problem below is now resolved.
I am trying to grab values from a stringstream into a vector of doubles.
std::ifstream filestream;
filestream.open("data.data");
if(filestream.is_open()){
filestream.seekg(0, std::ios::beg);
std::string line;
std::vector<double> particle_state;
particle_state.resize(6);
while(filestream >> line){
boost::tokenizer<> token(line);
int i = -1;
for(boost::tokenizer<>::iterator it=token.begin(); it!=token.end(); ++it){
std::cout << *it << std::endl; // This prints the correct values from the file.
if(i == -1){
// Ommitted code
}
else{
std::stringstream ss(*it);
ss >> particle_state.at(i); // Offending code here?
}
i ++;
}
turbovector3 iPos(particle_state.at(0), particle_state.at(1), particle_state.at(2));
turbovector3 iVel(particle_state.at(3), particle_state.at(4), particle_state.at(5));
// AT THIS POINT: cout produces "(0,0,0)"
std::cout << "ADDING: P=" << iPos << " V=" << iVel << std::endl;
}
filestream.close();
}
Contents of input file:
electron(0,0,0,0,0,0);
proton(1,0,0,0,0,0);
proton(0,1,0,0,0,0);
More on turbovector3:
turbovector3
is a mathematical vector class. (The important thing is that it works - essentially it is a vector with 3 items. It is initialised using the constructor with three doubles.)
Thanks in advance for help!
EDIT Modification of code:
std::stringstream ss(*it);
if(ss.fail()){
std::cout << "FAIL!!!" << std::endl; // never happens
}
else{
std::cout << ss.str() << std::endl; // correct value pops out
}
double me;
ss >> me;
std::cout << "double:" << me << std::endl; // correct value pops out again
particle_state.at(i) = me; // This doesn't work - why?
Upvotes: 0
Views: 1270
Reputation: 16705
Solution! I fluked and found this site: Link
The solution is to change the tokenizer to this:
boost::char_delimiters_separator<char> sep(false,"(),;");
boost::tokenizer<> token(line,sep);
Now it works!
Upvotes: 0
Reputation: 360
Do you increment i
in the omitted code? If not your else
clause never gets called. Try outputting the stringstream
buffer contents:
std::cerr << ss.str();
Also check if reading from ss
actually fails:
if (ss.fail())
std::cerr << "Error reading from string stream\n";
Upvotes: 1