新问题
boost::tokenizer<> token(line);
标记小数点!我该如何阻止这种情况发生?
以下问题现已解决。
我试图将字符串流中的值抓取到双精度矢量中。
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();
}
输入文件的内容:
electron(0,0,0,0,0,0);
proton(1,0,0,0,0,0);
proton(0,1,0,0,0,0);
有关turbovector3的更多信息:
turbovector3
是一个数学向量类。 (重要的是它可以工作 - 实际上它是一个包含3个项目的向量。它是使用带有三个双精度的构造函数初始化的。)
提前感谢您的帮助!
编辑修改代码:
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?
答案 0 :(得分:1)
你在省略的代码中增加i
吗?如果不是,则永远不会调用else
子句。尝试输出stringstream
缓冲区内容:
std::cerr << ss.str();
同时检查ss
的阅读是否确实失败:
if (ss.fail())
std::cerr << "Error reading from string stream\n";
答案 1 :(得分:0)
解决方案!我侥幸找到了这个网站:Link
解决方案是将tokenizer更改为:
boost::char_delimiters_separator<char> sep(false,"(),;");
boost::tokenizer<> token(line,sep);
现在有效!