Search code examples
c++vectorstructconstantspreprocessor

C++ Storing constant varibale names within a vector


My task is to write a preprocessor that replaces the constant variable with its actual value. To do this, I have created a struct and a vector to store the constant name and value. But unfortunately, I'm getting all kinds of compile errors. Can anyone spot any potential issues? Thank you in advance

using namespace std;
    
struct constantVariable 
{
    string constantName;
    string constantValue;
}; 

void defineReplace(string line)
{

    vector <constantVariable> constant;
    
    
    string token;
    
    stringstream stream(line);
    while(stream >> token)
    {
        
        if(token == "#define")
        {
        stream >> token;
        constant.constantName = token;
        stream >> token;
        constant.constantValue = token;
        break;
        }
    }
    
    constant.push_back(constant);
}

Solution

  • Simply use a new local variable inside your reading loop like this:

        while(stream >> token)
        {
            
            if(token == "#define")
            {
            constantVariable addconstant;
            stream >> token;
            addconstant.constantName = token;
            stream >> token;
            addconstant.constantValue = token;
            constant.push_back(addconstant);
            }
        }
    

    But take care with checking the input stream. It should not be done as easy as you did it... but that is another question.