Исключение памяти в программе - обработка файлов и строк - PullRequest
0 голосов
/ 21 октября 2011

Я получаю следующую ошибку: Unhandled exception at 0x7580b9bc in _ObjDraw.exe: Microsoft C++ exception: std::invalid_argument at memory location 0x0024f718..

При запуске:

    ifstream file(fileName);
    if(!file)
    {
        return;
    }

    faces = vector<Face>();
    string number = "";
    Face tFace;

    while(!file.eof())
    {
        getline(file, Buffer);
        if(Buffer[0] == 'f')
        {
            //Faces have vertices, normals, and textures
            size_t firstSpace = Buffer.find_first_of(' ', 0);
            size_t firstSlash = Buffer.find_first_of('/', firstSpace + 1);
            size_t nextSpace  = Buffer.find_first_of(' ', firstSpace + 1);
            size_t nextSlash = Buffer.find_first_of('/', firstSlash + 1);

            if(firstSlash == string::npos) //Implies that there are no normals or textures
            {
                do
                {
                    //Get the vertex number and add it to the face
                    nextSpace = Buffer.find_first_of(' ', firstSpace + 1);
                    number.assign(Buffer, firstSpace + 1, nextSpace - 1);
                    tFace.addVertex(stoi(number));

                    //Move to the next vertex
                    firstSpace = nextSpace;
                }while(firstSpace != string::npos);
            }
            else //implies that there are textures and/or normals
            {
                if(nextSlash < nextSpace) //Normal's are present
                {
                    do
                    {
                        //Get the vertex number
                        number.assign(Buffer, firstSpace + 1, firstSlash - 1);
                        tFace.addVertex(stoi(number));

                        //Get the normal
                        number.assign(Buffer, firstSlash + 1, nextSlash - 1);
                        if(number != "")
                        {
                            tFace.addTexture(stoi(number));
                        }

                        //Get the texture
                        number.assign(Buffer, nextSlash + 1, nextSpace - 1);
                        if(number != "")
                        {
                            tFace.addNormal(stoi(number));
                        }

                        //Get next positions
                        firstSpace = nextSpace;
                        firstSlash = Buffer.find_first_of('/', firstSpace);
                        nextSlash = Buffer.find_first_of('/', firstSlash + 1);
                        nextSpace = Buffer.find_first_of(' ', firstSpace + 1);

                    }while(firstSpace != string::npos);
                }
                else //Only textures
                {
                    do
                    {
                        //Get the vertex number
                        number.assign(Buffer, firstSpace + 1, firstSlash - 1);
                        tFace.addTexture(stoi(number));

                        //Get the normal number
                        number.assign(Buffer, firstSlash + 1, nextSpace - 1);
                        tFace.addNormal(stoi(number));

                        firstSpace = nextSpace;
                        nextSpace = Buffer.find_first_of(' ', firstSpace + 1);
                        firstSlash = Buffer.find_first_of('/', firstSlash + 1);

                    }while(firstSpace != string::npos);
                }
            }
            //Add tFace to face vector
            faces.push_back(tFace);
            tFace = Face();
        }
    }
    file.close();
}

123.obj имеет следующее содержимое: f 1//2 2//2 3//2 2//2 - Это вызывает исключениеf 1 2 3 4 или f 1/2/3 2/3/4 3/4/5 работает как надо.Проблема возникает только в случае двойной косой черты.При использовании файла с символом «//» первый оператор if должен быть ложным, и должен выполняться блок else, но по какой-то причине он заканчивается входом в первый цикл.firstSlash равно 3, а nextSlash равно 4, когда я вывожу их для проверки.Face и Vertex - это классы с соответствующими функциями-членами

Ответы [ 2 ]

0 голосов
/ 21 октября 2011

Просто включите отлов первого случайного исключения (в меню Отладка ==> Исключения ... или CTRL + ALT E в VS 2010) и запустите его в режиме отладчика. Он немедленно остановится, когда возникнет исключение, и вы сможете подняться по стеку к своему коду и (возможно) понять, что не так.

0 голосов
/ 21 октября 2011

find_first_of не выбрасывает, как и while или сравнение, поэтому ваша ошибка должна быть в одном из //code сегментов.

Вы должны вставить больше кода, если хотите получить ответ

--- после редактирования ---

Код может использовать гораздо больше проверок, вы проверяете только на firstSpace != npos в своем состоянии while, тогда как nextSpace и firstSlash могут легко быть npos во время следующей итерации.

...