I'm a programming student in my first C++ class, and for a recent project I did, I was unable to create an array of strings like I could do in C#:
string MONTHS[ARRAY_CAPACITY] = { "Jan", "Feb", "Mar", "April", "May", "June", "July", "Aug", "Sep", "Oct", "Nov", "Dec" };
// this yields many compiler errors in C++
Is it possible to do something similar in C++?
Thanks!
Yes, it does:
#include <string>
int main(void)
{
static const size_t Capacity = 12;
std::string Months[Capacity] = { "Jan", "Feb", "Mar", "April", "May",
"June", "July", "Aug", "Sep", "Oct",
"Nov", "Dec" };
}
Your errors were probably related to something else. Did you remember to use std::
? Without knowing, it could be anything. Was Capacity
the wrong size? Etc.
Note your code wasn't actually a constant array. This is:
#include <string>
int main(void)
{
static const size_t Capacity = 12;
static const std::string Months[Capacity] = { "Jan", "Feb", "Mar", "April",
/* ^^^^^^^^^^^^ */ "May", "June", "July", "Aug",
"Sep", "Oct", "Nov", "Dec" };
}
Also, you don't actually need Capacity
, as others will show, and you could use const char*
if you'd like, though you lose the std::string
interface.
The preferred method for an array of constant strings would probably be an array of cstrings,
const char* MONTHS[] = { "Jan", "Feb", "Mar", "April", "May", "June", "July",
"Aug", "Sep", "Oct", "Nov", "Dec" };
However, it can also be done with std::strings,
const string MONTHS[] = { string("Jan"), string("Feb"), ... };
Some compilers may not allow implicit conversion from char* to std::string when you initialize an array with curly braces; explicitly assigning an std::string constructed from a char* will fix that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With