Reputation: 169
string s;
cin>>s;
suppose s = "stackoverflow"
now if we access s[3]
, it should give out 'c'
will s[3]
be 'c'
or "c"
?
as in will it be a char data type or string data type?
Upvotes: 4
Views: 592
Reputation: 318
It is easiest to remember that std::string
is not a native type like char
is, but a wrapper class
that contains an array of chars
to form a string.
std::string
simply overloads the C array operator [] to return the char
at a given index, hence:
will
s[3]
be'c'
or"c"
?Answer:
'c'
Upvotes: 1
Reputation: 726569
std::string
is not a built-in type, so operator []
in s[3]
is a call to a member function defining this operator in the string template.
You can find the type by looking up the reference page for operator []
:
Returns a reference to the character at specified location pos.
To look up the type reference
and const_reference
from the documentation see "member types" section of std::basic_string<CharT>
template.
If you are looking for std::string
of length 1 starting at location 3, use substr
instead:
s.substr(3, 1); // This produces std::string containing "c"
Upvotes: 8
Reputation: 13934
It returns reference to the character as the operator []
is overloaded for std::string
char& operator[] (size_t pos);
const char& operator[] (size_t pos) const;
will s[3] be 'c' or "c"?
Character 'c', not string "c".
Upvotes: 8