I tried the below program:
#include <iostream>
#include <string>
int main ()
{
std::string str;
str[0] = 'o';
str[1] = 'k';
std::cout << str.length();
std::cout << "as a whole :";
std::cout << str << std::endl;
std::cout << "character by character :";
std::cout << str[0] << str[1] << std::endl;
return 0;
}
I do not understand why I can not print the string as a whole using the object variable and why the length is returning as 0
since clearly I have added the characters using the subscript operator as that would return char reference so I know that is legal.
In addition, I did not get any kind of exception. So there is that. Obviously, there is a lot happening behind the scenes in the std::string
class and I know I am missing something. Could someone help me with this?