C++ getline 在字符串开头添加 space

C++ getline adding space at beginning of string

这段代码一直在我试图检索的字符串前面抛出一个 space。

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;


        }
    }
}

这是我正在阅读的文件。我正在尝试获取名称,它一直在沙漠和草地前面放一个 space。

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

因为pos1 < pos2,所以pos1 - pos2 的结果是负数。由于这是存储在 size_t 类型的变量中,它是一个无符号整数,因此它变成了一个巨大的正数。
substr 被调用时带有大量数字作为第二个参数。在这种情况下,标准表示 "if the string is shorter, as many characters as possible are used"。我认为这里有些歧义,不同的实现可能会导致不同的行为。

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