Copy user input to char vector
<p>Quick disclaimer, this is a contrived example meant to simulate an issue I am seeing in my homework problem. To that end, using strings is out of the question; I can only use char arrays as per the instructor :(</p>

<p>What I am trying to do is continuously read input from the keyboard and store it in a <code>vector</code> . The problem is, whatever data I add to the <code>vector</code> is lost as soon as the <code>addData</code> function ends (when I try to view it, I see <code>\320\366\277_\377</code>). I believe this is due to the fact I am using a <code>vector&lt;char*&gt;</code>, so the <code>vector</code> can only use the data for as long as the <code>pointer</code> exists. However, my code cannot compile if I change it to a <code>vector&lt;char&gt;</code>, as I get errors saying <code>cannot convert char* to char</code>.</p>

<p>So, how can I save a <strong>char array</strong> (<em>not</em> a single char) to a vector element? Or, is there perhaps a better approach to this that would avoid the problem altogether?</p>

<pre><code>#include &lt;iostream&gt;
#include &lt;cstring&gt;
#include &lt;vector&gt;

using namespace std;
const int MAX_BUFFER_SIZE = 80;

// class declaration
class Example {
public:
    void getData ();
    void addData ( char * newData );
    void displayData ();

private:
    vector&lt;char*&gt; vec;
};

// main function
int main () {
    bool quitProg;
    int quit;
    quitProg = false;
    Example shoopDaWhoop; // buffers cannot overflow if you shoop da whoop
    while (!quitProg) {
        shoopDaWhoop.getData();
        shoopDaWhoop.displayData();
        cout &lt;&lt; "Type 1 if you want to exit... ";
        cin &gt;&gt; quit;
        if (quit == 1) {
            quitProg = true;
        }
    }
    return 0;
}

void Example::getData () {
    char userInput [MAX_BUFFER_SIZE];

    cout &lt;&lt; "Enter text: ";
    cin.get(userInput, MAX_BUFFER_SIZE - 1, '\n');
    if ( cin.fail() ) { // data is invalid
        // clear and reset input stream
        cin.clear(ios::goodbit);
        cin.ignore(INT_MAX,'\n');
        // alert user they entered bad data
        cout &lt;&lt; "That was bad data!" &lt;&lt; endl;
    }
    else {
        // data is good, pass it to addData
        addData( userInput );
    }
}

void Example::addData ( char * newData ) {
    vec.push_back(newData);
    cout &lt;&lt; "You entered: " &lt;&lt; vec.back() &lt;&lt; endl;


}
void Example::displayData () {
    for (int i=0; i&lt;vec.size(); i++) {
        cout &lt;&lt; "Item " &lt;&lt; i &lt;&lt; ": " &lt;&lt; vec[i] &lt;&lt; endl;
    }
</code></pre>

<p>}</p>
