Вектор структур и пользовательских функций, действующих вверх - PullRequest
0 голосов
/ 30 апреля 2011

Я пытаюсь создать проект C ++ для моего класса Geometry. Я хочу, чтобы пользователь мог хранить и получать доступ к переменным. Для этого я создал struct var, содержащий string name и float value. У меня есть vector < var > varList для хранения переменных. Тем не менее, после компиляции программа не работает хорошо ... вообще. Сначала он проверяет, существует ли переменная «собака», чего, очевидно, нет, и находит, что она существует. Затем он пытается изменить переменную dog и changeVar вместо возврата ERR_NONEXISTENT возвращает правильный статус выхода ноль. После проверки переменной он видит, что ее не существует. Затем, при попытке перечислить все переменные, он создает ошибку сегментации. Смотрите ниже:

Building Generator 1.0 Alpha
   Variable Systems Test   
~~~~~~~~~~~~~~~~~~~~~~~~~~~

Enter a variable name:
dog
Enter a value (A FLOAT!):
2.2
Checking to see if dog exists.
It exists!
Changing variable. Function returned 0
Enter a variable to check:
dog
Variable "dog" doesn't exist!
Segmentation fault

Мой источник здесь . Я компилирую с Eclipse Helios, с G ++ 4.2.1, на Mac 10.6.7 Snow Leopard. Что происходит?

Если это не сработает, я постараюсь выяснить std::map

Кроме того, это только мой второй вопрос здесь; пожалуйста, извините (но сообщите мне) о любых ошибках форматирования.

Спасибо

BF

РЕДАКТИРОВАТЬ: Вот код:

vsystem.cpp

/*
 * vsystem.cpp
 *
 *  Created on: Apr 29, 2011
 *      Author: wjc
 */


#include <string>
#include <vector>
#include <sstream>
#include "vsystem.h"

using namespace std;

vector <var> varList;

int addVar(string varName, float value){
    // Check to see if varName already exists
    bool varExists = false;
    for (unsigned int i=0; i<varList.size(); i++){
        if (varList[i].name == varName){
            varExists = true;
            return ERR_VAR_EXISTS;
        }
    }

    // Good! The variable doesn't exist yet.
    var tempVar;
    tempVar.name = varName;
    tempVar.value = value;
    varList.push_back(tempVar);
    return 0;
}

int changeVar(string varName, float newValue){
    // Check to see if varName exists
    for(unsigned int i=0; i<varList.size(); i++){
        if(varList[i].name != varName){    // If it doesn't match…
            if (i == varList.size() - 1) // And it's the last one…
                return ERR_NONEXISTENT;  // Uh oh!
        } else { // Found it!
            varList[i].value = newValue;
        }
    }
    return 0;
}

fetchResult fetchVar(string varName){
    fetchResult returnValue;
    // Check to see if varName exists
    for(unsigned int i=0; i<varList.size(); i++){
        if(varList[i].name != varName){     // If it doesn't match…
            if (i == varList.size() - 1){ // And it's the last one…
                returnValue.good = false; // Uh oh!
                returnValue.result = -1;
            } else {
                returnValue.good = true;
                returnValue.result = varList[i].value;
            }
        }
    }
    return returnValue;
}

bool checkVar(string varName){
    // Check to see if varName exists
    for(unsigned int i=0; i<varList.size(); i++){
        if(varList[i].name != varName){  // If it doesn't match…
            if (i == varList.size() - 1) // And it's the last one…
                return false;            // It's not here.
        }else break;
    }
    return true;
}

vector < var > getVarList(){
    return varList;
}


string getVarList(string varDelim, string valueDelim){
    stringstream final;
    for (unsigned int i=0; i<varList.size()-1; i++){
        final<<varList[i].name<<valueDelim<<varList[i].value<<varDelim;
        // add variable name, delim 1 (probably tab), variable value, delim 2 (probably newline)
    }
    final<<varList.back().name<<valueDelim<<varList.back().value;
    // same, but don't add a newline (or other)
    return final.str();
}

vsystem.h

/*
 * vsystem.h
 *
 *  Created on: Apr 29, 2011
 *      Author: wjc
 */


#include <vector>
#include <string>
#include "consts.h"

using namespace std;

#ifndef VSYSTEM_H_
#define VSYSTEM_H_

struct fetchResult {
    float result;
    bool good;
};

struct var {
    string name;
    float value;
};

int addVar(string varName, float value);
int changeVar(string varName, float newValue);
fetchResult fetchVar(string varName);
bool checkVar (string varName);

vector < var > getVarList();
string getVarList(string varDelim, string valueDelim);

#endif /* VSYSTEM_H_ */

ui.h

/*
 * ui.cpp
 *
 *  Created on: Apr 26, 2011
 *      Author: wjc
 */

#include <iostream>
#include <vector>

#include "filedaemon.h"
#include "vsystem.h"

using namespace std;

int runUI(){
    cout << "   Variable Systems Test   "<<endl;
    cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl;
    cout << endl;
    cout<<"Enter a variable name:"<<endl;
    string varname;
    cin>>varname;
    cout<<"Enter a value (A FLOAT!):"<<endl;
    float value;
    cin>>value;
    cout<<"Checking to see if "<<varname<<" exists."<<endl;
    bool alreadythere = checkVar(varname);
    alreadythere ? cout<<"It exists!"<<endl : cout<<"It doesn't exist."<<endl;
    if (alreadythere){
        cout<<"Changing variable. Function returned "<<changeVar(varname, value)<<endl;
    } else {
        cout<<"Setting variable. Function returned "<<addVar(varname, value)<<endl;
    }
    cout<<"Enter a variable to check:"<<endl;
    string varcheck;
    cin>>varcheck;
    fetchResult result = fetchVar(varcheck);
    if(! result.good){
        cout<<"Variable \""<<varcheck<<"\" doesn't exist!"<<endl;
    } else {
        cout<<"Variable \""<<varcheck<<"\" is equal to "<<result.result<<endl;
    }
    cout<<getVarList("\n","\t")<<endl;
    string exitstr;
    cin>>exitstr;
    return 0;
}

main.cpp просто вызывает runUI ()

1 Ответ

0 голосов
/ 30 апреля 2011

То, как вы зацикливаетесь на векторе и возвращаете true / false, странно, и ваше приложение падает из-за checkVar().

. Я рекомендую вам изменить все циклы на varList, которые ищутэлемент к чему-то более простому и удобному для чтения, например:

bool checkVar(string varName)
{
    // Check to see if varName exists
    for (unsigned int i=0; i<varList.size(); i++)
    {
        if (varList[i].name == varName)
        {   // If matches,
            return true;        
        }   
    }   

    // If execution reaches here, it means it didn't found a match
    return false;
}

Это решает проблему сбоя.Я не знаю, есть ли в вашем приложении какие-либо другие ошибки, но это мой текущий вывод:

Building Generator 1.0 Alpha
   Variable Systems Test   
~~~~~~~~~~~~~~~~~~~~~~~~~~~

Enter a variable name:
dog
Enter a value (A FLOAT!):
2.2
Setting variable. Function returned 0
Enter a variable to check:
alpha
Variable "alpha" doesn't exist!
dog     2.2

РЕДАКТИРОВАТЬ:

Другая проблема связана с вашими определениями:ERR_NONEXISTENT и ERR_VAR_EXISTS оба 1.Они должны иметь разные значения!Я вставляю соответствующий код ниже:

consts.h :

#ifndef CONSTS_H_
#define CONSTS_H_

#define VERSION "1.0 Alpha"

// Variable errors
#define ERR_NONEXISTENT 0
#define ERR_VAR_EXISTS 1

// File r/w errors
#define ERR_FILE_OPEN 2

#endif /* CONSTS_H_ */

vsystem.cpp :

#include <string>
#include <vector>
#include <sstream>
#include "vsystem.h"

using namespace std;

vector <var> varList;

int addVar(string varName, float value){
        // Check to see if varName already exists
        bool varExists = false;
        for (unsigned int i=0; i<varList.size(); i++){
                if (varList[i].name == varName){
                        varExists = true;
                        return ERR_VAR_EXISTS;
                }
        }

        // Good! The variable doesn't exist yet.
        var tempVar;
        tempVar.name = varName;
        tempVar.value = value;
        varList.push_back(tempVar);
        return ERR_NONEXISTENT;
}

int changeVar(string varName, float newValue){
        // Check to see if varName exists
        for(unsigned int i=0; i<varList.size(); i++){
                if(varList[i].name == varName)
        {   // If it match, replace the value
                        varList[i].value = newValue;
            return ERR_VAR_EXISTS;
                }
        }

    return ERR_NONEXISTENT;  // Uh oh!
}

fetchResult fetchVar(string varName){
        fetchResult returnValue;
        // Check to see if varName exists
        for(unsigned int i=0; i<varList.size(); i++){
                if(varList[i].name == varName){     // If it matches
                        if (i == varList.size() - 1)
            {
                                returnValue.good = true;
                                returnValue.result = varList[i].value;
                    return returnValue;
                        }
                }
        }

    returnValue.good = false; // Uh oh!
        returnValue.result = -1;
        return returnValue;
}

bool checkVar(string varName)
{
        // Check to see if varName exists
        for(unsigned int i=0; i<varList.size(); i++){
                if(varList[i].name == varName)
        {   // If matches, return true
                    return true;
                }
        }

    // If execution reaches here, it means it didn't found a match
        return false;
}

vector < var > getVarList(){
        return varList;
}


string getVarList(string varDelim, string valueDelim){
        stringstream final;
        for (unsigned int i=0; i<varList.size()-1; i++){
                final<<varList[i].name<<valueDelim<<varList[i].value<<varDelim;
                // add variable name, delim 1 (probably tab), variable value, delim 2 (probably newline)
        }
        final<<varList.back().name<<valueDelim<<varList.back().value;
        // same, but don't add a newline (or other)
        return final.str();
}
...