First of all, to answer your doubt about the type: sequence[i]
is of type char
.
Next, concerning your implementation: to start with, as many people have suggested in the comments, I recommend not getting the length of the string separately from the string itself, because the length of the input string may be different from the declared length, and this may cause all sort of problems (ever heard of the infamous bug heartbleed?)
So, this is the minimum I would do:
string sequence; // string sequence
cin >> sequence;
char charList[sequence.length()]; // list of the characters
for (int i = 0; i < sequence.length(); i++) {
charList[i] = sequence[i];
}
However, this is still not satisfactorily enough because the above code is not conformant. In other words it is not valid C++ because C++ does not really allow variable-length arrays. Depending on the compiler you may get away with it, for instance g++ accepts it, see https://stackoverflow.com/a/15013295/12175820
But even with g++, if you compile with the -pedantic
flag you'll get the following warning:
str2arr.cpp:10:8: warning: ISO C++ forbids variable length array ‘charList’ [-Wvla]
10 | char charList[sequence.length()]; // list of the characters
which compounded to -Werror
gives a full-blown compilation error:
str2arr.cpp:10:8: error: ISO C++ forbids variable length array ‘charList’ [-Werror=vla]
10 | char charList[sequence.length()]; // list of the characters
Plus you might have trouble with more advanced usage, for instance I've just discovered that typeid(charList)
won't compile with a variable-length array...
So the real way to do this in C++ would be using pointers and dynamic-memory allocation, in the heap, using operator new
:
string sequence; // string sequence
cin >> sequence;
char* charList = new char[sequence.length()]; // list of the characters
for (int i = 0; i < sequence.length(); i++) {
charList[i] = sequence[i];
}
the above code is valid C++ accepted by any compiler.