4
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?

1

3 Answers 3

8

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" 
Sign up to request clarification or add additional context in comments.

2 Comments

Perhaps you could also explain how to look up the return type "reference" in the parent page and untangle the template usage to finally get "char&".
@aschepler Thanks!
8

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".

Comments

1

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'

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.