I tried to print the address of each character of std::string
. But I amn't understanding what is happening internally with std::string
that is resulting this output while for the array it is giving the address as I expected. Could someone please explain what is going on?
#include <iostream>
#include <string>
using namespace std;
int main(){
string str = "Hello";
int a[] = {1,2,3,4,5};
for( int i=0; i<str.length(); ++i )
cout << &str[i] << endl;
cout << "**************" << endl;
for( int i=0; i<5; ++i )
cout << &a[i] << endl;
return 0;
}
Output:
Hello
ello
llo
lo
o
**************
0x7fff5fbff950
0x7fff5fbff954
0x7fff5fbff958
0x7fff5fbff95c
0x7fff5fbff960
You can access the characters in a string by referring to its index number inside square brackets [] .
C++ at() function is used for accessing individual characters. With this function, character by character can be accessed from the given string.
The strchr() function finds the first occurrence of a character in a string. The character c can be the null character (\0); the ending null character of string is included in the search. The strchr() function operates on null-ended strings.
std::string class in C++ C++ has in its definition a way to represent a sequence of characters as an object of the class. This class is called std:: string. String class stores the characters as a sequence of bytes with the functionality of allowing access to the single-byte character.
When a std::ostream
tries to print a char*
it assumes it's a C-style string.
Cast it to a void*
before printing and you will get what you expect:
cout << (void*) &str[i] << endl;
or you may use the old printf
printf("\n%x",&s[i]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With