storing a c++ string into a char* vector -
i'm trying store string vector of pointers. starting point of code. vector store words user types in , either add vector if vector doesn't have or show word in vector.
i tried use strcpy() told me use strcpy_s(). did , crashes every time no error. can give me insight going on here.
vector<char*> wordbank; string str; cin >> str; wordbank[0] = new char[str.length() + 1]; strcpy_s(wordbank[0], str.length() + 1 , str.c_str() ); cout << wordbank[0]; delete[] wordbank[0];
i not consider vector<char*> wordbank;
c++ code, rather c code happens use c++ features.
the standard library in c++ can make life easier. should use std::vector<std::string>
instead.
vector<string> wordbank; wordbank.push_back(str);
it avoid pointer stuff, need not memory management (which reason rid of pointers).
for strcpy_s
, it's safer version of strcpy
, because have explicitly specify size of target buffer, can avoid buffer overflows during copies.
however, strcpy_s
non-standard , ms specific, never use strcpy_s
unless want code compiled on msvs. use std::copy
instead.
Comments
Post a Comment