Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does C++ support constant arrays of type string?

Tags:

c++

arrays

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!

like image 290
Alex Avatar asked Feb 02 '10 15:02

Alex


2 Answers

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.

like image 94
GManNickG Avatar answered Sep 20 '22 14:09

GManNickG


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.

like image 33
Collin Dauphinee Avatar answered Sep 20 '22 14:09

Collin Dauphinee