2

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

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;
}
6
  • 3
    For std::string s2, s2[i] exhibits undefined behavior when i >= s2.size(). Which it is in your first example, ass2.size() == 0 Commented Aug 29, 2020 at 20:36
  • 4
    Instead of looping simply s2 = s1; would copy a std::string correctly Commented Aug 29, 2020 at 20:36
  • @UnholySheep My assignment says without using inbuilt functions please help me with another way to gain marks. Commented Aug 29, 2020 at 20:38
  • 1
    You cannot copy a std::string without using "inbuilt functions" - the internals of a std::string are not something you can just mess with, they are hidden from you (since there's a lot of optimizations going on in there). Commented Aug 29, 2020 at 20:41
  • 2
    s2[i] calls std::string::operator[]. Why is it OK to call that, but not std::string::operator=? What exactly is the definition of "inbuilt function", and how does it manage to distinguish between these two member functions of std::string class? Commented Aug 29, 2020 at 20:45

1 Answer 1

1

In your case, s2 is initialized to an empty string with a length of 0, so you can't write past the bounds. If you want to, you must first resize it:

s2.resize(s1.length());
for(i=0; s1[i]!='\0'; ++i)
{
    s2[i]=s1[i];
}

Also, c++ std::string does not need a terminating nullbyte, unlike C strings.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.