Please explain why is this giving an error but the other on is running fine The following code gives the error:
#include <iostream>
#include <string>
#include <conio.h>
#include <math.h>
#include <iomanip>
#include <string.h>
using namespace std;
int main()
{
string s1,s2;
int i;
cout << "Enter the string to copy into another string : ";
getline(cin,s1);
for(i=0; s1[i]!='\0'; ++i)
{
s2[i]=s1[i];
}
s2[i]='\0';
cout<<"\n\nCopied String S2 is : "<<s2;
return 0;
}
Error looks like this
But this works perfectly fine
#include <iostream>
#include <string>
#include <conio.h>
#include <math.h>
#include <iomanip>
#include <string.h>
using namespace std;
int main()
{
char s1[100], s2[100], i;
cout << "Enter the string to copy into another string : ";
cin>>s1;
for(i=0; s1[i]!='\0'; ++i)
{
s2[i]=s1[i];
}
s2[i]='\0';
cout<<"\n\nCopied String S2 is : "<<s2;
return 0;
}

std::string s2,s2[i]exhibits undefined behavior wheni >= s2.size(). Which it is in your first example, ass2.size() == 0s2 = s1;would copy astd::stringcorrectlystd::stringwithout using "inbuilt functions" - the internals of astd::stringare not something you can just mess with, they are hidden from you (since there's a lot of optimizations going on in there).s2[i]callsstd::string::operator[]. Why is it OK to call that, but notstd::string::operator=? What exactly is the definition of "inbuilt function", and how does it manage to distinguish between these two member functions ofstd::stringclass?