2015-07-11 196 views
0

这段代码不断在我尝试检索的字符串前面投掷一个空格。C++ getline在字符串开头添加空格

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 will be dynamic based on what the text file defines as the pixel sizes 
     texture.width = 32; 
     if(line.find("<name>") != std::string::npos) 
     { 
      std::size_t pos1 = line.find("<name>") + 6; //Search for the name of the texture 
      std::size_t pos2 = line.find(";", pos1); 
      std::size_t namesize = pos1 - pos2; 
      texturename = line.substr(pos1, namesize); 
      std::cout << texturename << std::endl; 


     } 
    } 
} 

这是我正在阅读的文件。我试图获得这个名字,它一直在沙漠和草地上放置一个空间。

<collection>tilemapsheet; 
<ratio>32; 
<name>desert; <coords>x=0 y=0; 
<name>grass; <coords>x=32 y=0; 
+0

如果任何人有更好的建议,如何做到这一点以及我会很感激任何建设性的批评。我基本上搜索某个单词,然后读取信息以设置sfml中的纹理 – Joshua

+3

您确定该空间没有被前面的“cout”调用输出吗?另外(不相关的),你应该把',pos1'放在你搜索的末尾;'''如果前面有一个'

+0

这是我的代码中的第一个cout调用。谢谢你的提示。它为沙漠和草地提供了一个空间。它在沙漠之后立即打印草而不会离开while循环。 – Joshua

回答

0

由于pos1是< pos2,所以pos1-pos2的结果是负数。由于这是存储在size_t类型的变量中的,所以它是一个无符号整数,它变成了一个巨大的正数。
substr正在被大量调用作为第二个参数。在这种情况下,标准说“如果字符串更短,尽可能多的字符被使用”。我认为这里有一些不明确的地方,不同的实现可能会导致不同的行为。

http://www.cplusplus.com/reference/string/string/substr/

让我们POS1和POS2的打印值,看看发生了什么。

 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; 

在我的情况,我有以下值

0, 6, 12, 18446744073709551610 
texturename: desert; <coords>x=0 y=0; 
0, 6, 11, 18446744073709551611 
texturename: grass; <coords>x=32 y=0; 

当我尝试(POS2 - POS1),我得到了正常的预期行为。

0, 6, 12, 6 
texturename: desert 
0, 6, 11, 5 
texturename: grass 
+0

所以我切换了pos1和pos2变量。不知道我是怎么搞砸的......但由于某种原因,现在pos2变成了一个非常大的正数。我不明白为什么要么 – Joshua

+0

好,所以这是因为找到pos2它的值的函数返回为'std :: string :: npos'我不完全确定为什么。 – Joshua

+0

......这是因为我在添加分号后从未保存过文本文件。感谢帮助我的愚蠢错误= P。有没有更好的方法来做到这一点? – Joshua