int main() {
string str[5] = "ABCD";
std::cout << str[3] << std::endl;
std::cout << str[0] << std::endl;
return 0;
}
This code prints:
ABCD
ABCD
I didn't get it, how str[3]
prints ABCD
?
Compiler: GCC 6.3
int main() {
string str[5] = "ABCD";
std::cout << str[3] << std::endl;
std::cout << str[0] << std::endl;
return 0;
}
This code prints:
ABCD
ABCD
I didn't get it, how str[3]
prints ABCD
?
Compiler: GCC 6.3
The code is not valid C++ code and it shouldn't compile. And it doesn't with clang and gcc version above 7. It is most likely a bug in older version of gcc that got fixed in version 7.
std::string str[5]
What you have here is a C array of 5 elements of std::string
. This is how you would initialize it:
std::string strings[5] = {"1st string", "2nd string", "3rd string", "4th string", "5th string"};
In this case strings[0]
would be "1st string"
and strings[3]
would be "4th string"
.
However don't do this. Don't use C arrays in C++. Use std::vector
or std::array
if you need an array of strings: std::array<std::string> strings
or std::vector<std::string> strings
.
That being said, I suspect that you want just one string, aka:
std::string str = "ABCD";
In this case str[0]
is 'A'
and str[3]
is 'D'
You can try this to get your code compile:
string str[5] = {"ABCD", "", "", "", ""};
str[3]
in your code means 4the string of the array if you get it compiled.
But you most likely meant to have:
char str[5] = "ABCD";
string and char are not the same thing. If you want to access single char in a string you don’t need an array of strings. A single string is all you need:
string str = "ABCD";
std::cout << str[3] << std::endl;
What's happening is:
the line string str[5] = "ABCD";
is simply copying/initializing all the indexes of variable str
with the value ABCD
like str[0] = "ABCD", str[1] = "ABCD"
, and so on.
So, when you run std::cout << str[3] << std::endl;
and std::cout << str[0] << std::endl;
, you're getting the value from the respective index of the string array str
.