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 🙁
What I am trying to do is continuously read input from the keyboard and store it in a vector . The problem is, whatever data I add to the vector is lost as soon as the addData function ends (when I try to view it, I see \320\366\277_\377). I believe this is due to the fact I am using a vector<char*>, so the vector can only use the data for as long as the pointer exists. However, my code cannot compile if I change it to a vector<char>, as I get errors saying cannot convert char* to char.
So, how can I save a char array (not a single char) to a vector element? Or, is there perhaps a better approach to this that would avoid the problem altogether?
#include <iostream>
#include <cstring>
#include <vector>
using namespace std;
const int MAX_BUFFER_SIZE = 80;
// class declaration
class Example {
public:
void getData ();
void addData ( char * newData );
void displayData ();
private:
vector<char*> 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 << "Type 1 if you want to exit... ";
cin >> quit;
if (quit == 1) {
quitProg = true;
}
}
return 0;
}
void Example::getData () {
char userInput [MAX_BUFFER_SIZE];
cout << "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 << "That was bad data!" << endl;
}
else {
// data is good, pass it to addData
addData( userInput );
}
}
void Example::addData ( char * newData ) {
vec.push_back(newData);
cout << "You entered: " << vec.back() << endl;
}
void Example::displayData () {
for (int i=0; i<vec.size(); i++) {
cout << "Item " << i << ": " << vec[i] << endl;
}
}
Use a
std::vector<std::string>, that should “just work” with your existing code.Since you cant do this with
std::string(which would have been the proper way to use the language), the you a nested vector, like this:Then in your
addDatafunction: