Using ifstream to read floats
我正在尝试使用ifstream从.out文件中读取一系列浮点,但是如果随后输出它们,它们是不正确的。
这是我的输入代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | float x, y, z; ifstream table; table.open("Resources/bones.out"); if (table.fail()) { cout <<"Can't open table" << endl; return ; } table >> x; table >> y; table >> z; cout << x <<"" << y <<"" << z << endl; table.close(); |
我的输入文件:
1 2 3 4 | 0.488454 0.510216 0.466979 0.487242 0.421347 0.472977 0.486773 0.371251 0.473103 ... |
现在,为了测试,我只是把第一行读到
1 | 1 0 2 |
我为什么没有得到正确的输出有什么想法吗?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | #include <fstream> #include <strtk.hpp> // http://www.partow.net/programming/strtk std::string filename("Resources/bones.out"); // assuming the file is text std::fstream fs; fs.open(filename.c_str(), std::ios::in); if(fs.fail()) return false; const char *whitespace =" \t \f"; std::string line; std::vector<float> floats; std::vector<std::string> strings; float x = 0.0, y = 0.0, z = 0.0; std::string xs, ys, zs; // process each line in turn while( std::getline(fs, line ) ) { // Removing beginning and ending whitespace // can prevent parsing problems from different line endings. // formerly accomplished with boost::algorithm::trim(line) strtk::remove_leading_trailing(whitespace, line); // strtk::parse combines multiple delimiters in these cases if( strtk::parse(line, whitespace, floats ) ) { std::cout <<"succeed" << std::endl; // floats contains all the values on the in as floats } if( strtk::parse(line, whitespace, strings) ) { std::cout <<"succeed" << std::endl; // strings contains all the values on the in line as strings } if( strtk::parse(line, whitespace, x, y, z) ) { std::cout <<"succeed" << std::endl; // x,y,z contain the float values. parse fails if more than 3 floats are on the line } if( strtk::parse(line, whitespace, xs, ys, zs) ) { std::cout <<"succeed" << std::endl; // xs,ys,zs contain the strings. parse fails if more than 3 strings are on the line } } |
这就是我解决问题的方法。您可以选择分析数据的方法。
我之前已经处理过这个问题,我想做的事情是下面的代码,您可以一行一行地读取文本文件,并使用getline和字符串将twext放入变量中。您不必使用数组,因为它仅限于元素,但是使用向量,这样您就可以动态添加。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | string xs; string ys; string zs; ifstream infile; someArray[50]; infile.open("some file.txt"); if (!infile) { cout <<"no good file failed! " << endl; } while (infile.good()) { for (int i = 0; i < 49; ++i) { getline(infile, xs); //Saves the line in xs. infile >> p[i].xs; getline(infile, ys, ','); infile >> p[i].ys; getline(infile, zs, ','); infile >> p[i].zs; } //infile >> p.fromFloor; */ } infile.close(); } |