If a string\'s length is determined at compile-time, how can I properly initialize it?
#include
int length = 3;
string word[length]; //invalid
How about the following?
string word;
word.resize(3);
word[0] = 'a';
word[1] = 'b';
word[2] = 'c';
More on resizing a string: http://www.cplusplus.com/reference/string/string/resize/
std::string
does not support lengths known at compile time. There's even a proposal for adding compile time strings to the C++ standard.
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4121.pdf
For now you're out of luck. What you can do is use static const char[]
which does support compile time constant strings but obviously lacks some of the niceties of std::string
. Whichever is appropriate depends on what you're doing. It may be that std::string
features are unneeded and static char[]
is the way to go or it may be that std::string
is needed and the runtime cost is neglibible (very likely).
The syntax you are trying will work with static const char[]
:
static const char myString[] = "hello";
Any constructor for std::string
shown in the other answers is executed at runtime.
You can initialize your string like this:
string word = "abc"
or
string word(length,' ');
word[0] = 'a';
word[1] = 'b';
word[2] = 'c';
A string is mutable and it's length can changed at run-time. But you can use the "fill constructor" if you must have a specified length: http://www.cplusplus.com/reference/string/string/string/
std::string s6 (10, 'x');
s6
now equals "xxxxxxxxxx".
You are probably looking for:
string word(3, ' ');