fstream - C++ getline adding space at beginning of string -
this bit of code keeps throwing space in front of strings i'm attempting retrieve.
void texture_manager::loadsheet(std::string filename, std::string textfile) { std::ifstream infofile(textfile); if (infofile.is_open()) { std::string line; while(std::getline(infofile, line )) { std::string texturename; sf::intrect texture; texture.height = 32; //these dynamic based on text file defines pixel sizes texture.width = 32; if(line.find("<name>") != std::string::npos) { std::size_t pos1 = line.find("<name>") + 6; //search name of texture std::size_t pos2 = line.find(";", pos1); std::size_t namesize = pos1 - pos2; texturename = line.substr(pos1, namesize); std::cout << texturename << std::endl; } } }
here's file i'm reading from. i'm trying name , keeps putting space in front of desert , grass.
<collection>tilemapsheet; <ratio>32; <name>desert; <coords>x=0 y=0; <name>grass; <coords>x=32 y=0;
since pos1 < pos2, result of pos1 - pos2 negative number. since being stored in variable of type size_t, unsigned int, becomes huge positive number.
substr being called large number 2nd parameter. in case, standard says "if string shorter, many characters possible used". think there ambiguity here , different implementations may lead different behavior.
http://www.cplusplus.com/reference/string/string/substr/
let print values of pos1 , pos2 see happening.
std::size_t pos0 = line.find("<name>"); std::size_t pos1 = line.find("<name>") + 6; //search texture std::size_t pos2 = line.find(";", pos1); std::size_t namesize = pos1 - pos2; std::cout << pos0 << ", " << pos1 << ", " << pos2 << ", " << namesize << std::endl; texturename = line.substr(pos1, namesize); std::cout << "texturename: " << texturename << std::endl;
in case, got following values
0, 6, 12, 18446744073709551610 texturename: desert; <coords>x=0 y=0; 0, 6, 11, 18446744073709551611 texturename: grass; <coords>x=32 y=0;
when tried (pos2 - pos1), got normal expected behavior.
0, 6, 12, 6 texturename: desert 0, 6, 11, 5 texturename: grass
Comments
Post a Comment