Robert
Robert

Reputation: 1

Loading Data into a vector of structs

I am trying to make a basic text editor and I'm having trouble loading the data in the struct using push_back.

Here is the struct

struct LineInfo
{       
    int lineNumber;         
    string text;            
};

Here is the main program

vector<LineInfo> globalDocument;

int main()
{
    cout << "COSC 120 line editing system now running." << endl << endl;
    bool done = false;
    while ( !done )
    {
        cout << "> ";
        string inputBuffer;
        getline( cin, inputBuffer );
        int lineNumber;
        splitLineNumberAndText( inputBuffer, lineNumber );
        ptr.push_back( &lineNumber );
        if ( lineNumber > 0 )
            handleTextLine( inputBuffer, lineNumber );
        else
            done = handleSystemCommand( inputBuffer );
    }

    cout << endl << "COSC 120 line editing system has shut down. Bye." << endl;
    return 0;
}

This receives a line number and text from input then splits it up into an int and a string and sends it to handleTextLine

Here is the function

void handleTextLine( const string& s, int lineNumber2 )
{
    globalDocument.lineNumber.push_back(lineNumber2);
    globalDocument.text.push_back(s);
}

Upvotes: 0

Views: 245

Answers (1)

Emile Cormier
Emile Cormier

Reputation: 29229

vector<LineInfo> globalDocument is a vector of LineInfo structs, so you must push_back LineInfo objects into it:

void handleTextLine( const string& s, int lineNumber2) {
    LineInfo li;
    li.lineNumber = lineNumber2;
    li.text = s;
    globalDocument.push_back(li);
}

Or, using struct initialization syntax:

void handleTextLine( const string& s, int lineNumber2) {
    LineInfo li = {lineNumber2, s};
    globalDocument.push_back(li);
}

You can get even more compact insertion code if you declare a constructor for LineInfo:

struct LineInfo {

    // Default constructor
    LineInfo() : lineNumber(0) {}

    // Constructor taking 2 arguments
    LineInfo(int n, string s) : lineNumber(n), text(s) {}

    int lineNumber;
    string text;
};

void handleTextLine( const string& s, int lineNumber2) {
    globalDocument.push_back(LineInfo(lineNumber2, s));
}

Upvotes: 2

Related Questions