Edit3: I intend to return to this to simplify the question and run through the list of responses in which the same answers keep recurring so as to explain why they don't work.
Edit: Explanation for why the question is unique: None of the other answers to the question answer the question. The question is unanswered. Basically as I can express it:
- There is a const string = "Hello";
- How to I get the string length at compile time?
Edit2: I've asked the question here again because I'm inundated with solutions which don't work. I'm getting exhausted with repeat explanations of why they don't work. The only answer which works is exactly what I had before I came here to find a better way of doing it.
The basic scenario which I cannot change is this:
I have a string declaration ( it's mandated this way ):
const string LETTERS = "Random Sentence";
Next, I need to perform a series of separate operations on the string.
So, what I'm doing is trying to declare a second mutable string to be the container for the outcome of those operations:
e.g. string ALPHABETICISED[15];
But, that is unwise. If it were a long program and I change the candidate LETTERS, then I must not forget to change the 15 to the new value manually. If there are several cases, it's accident prone.
What I'd like to do is something like:
int size = (int)LETTERS.length();
string alphabeticised[size];
But that is invalid, for two reasons:
- It would make an array of strings, it won't set the length of one.
- It won't evaluate at compile time anyway, so it will throw a non-constant expression error when I try to compile it because it doesn't have a substitution value yet.
Some recommendations use a constexpr, which would help, except for the fact it must compile against MSVC 2012, which basically limits me to c++98 convention. In any case, I can't use a constexpr in MSVC 2012.
Also, and for similar reasons, I'd like to use this size in the loops which will operate on the string, for example:
for ( int x = 0; x < LETTERS.length(); x++ ) {
// Do stuff, for random example:
incremented[x] = ++LETTERS[x];
}
Again though, I :shouldn't: need to find LETTERS.length at runtime! I already know what it will be every time.
So, how do I discover and use the string length at compile time, so I dont' have to find it during run time?
Caveats:
The solution must compile against MSVC 2012, which is roughly c++98 compliant and with very scant C++11 features, not even constexpr.
Also, I have no access to a debugger so I can't find out, as in a similar questions, if the compiler has subbed LETTERS.Length() for a constant expression.
In short, how to I declare a new string with the same length as a constant string with known length at compile time against MSVC 2012?
It seemed so simple! People must need to do this all the time? Allocate some volatile memory for a the result of an operation on a nonmutable array?