1

I have a string type and I am trying to copy this into another string type char by char but when I try to display the output of new copied it is coming as blank. Where as when I try to output char by char for that copied string length its alright. Please see this small code and output for better understanding.

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string name = "Tom";
    string temp;
    int i = 0;
    for(; i < name.length(); ++i)
    {
        temp[i] = name[i];
    }
    cout<<name<<endl;     //gives the output Tom
    cout<<temp<<endl;     //gives blank
    for(int i = 0; i < name.length(); ++i)
    {
        cout<<temp[i];    //gives output char by char
    }
}

Output :

Tom

Tom 

I know there are other possible ways to achieve what I am trying to do but just out of thought tried this and it didn't work. So looking for some explanation.

2

3 Answers 3

2

Note that temp is empty, its length is 0. Then temp[i] = name[i]; leads to undifined behavior; anything is possible but nothing is guaranteed.

You can give it an initial length like:

string name = "Tom";
string temp(name.length(), '\0');
Sign up to request clarification or add additional context in comments.

2 Comments

I get that, still not clear as why in for loop it was giving right answer.
@rakeshsinha Undefined behavior means anything is possible; but nothing is guaranteed.
0

You have to allocate data for the temp string to change any data in it.

string temp(name.length(),'\0');

Comments

0
for(; i < name.length(); ++i) temp.push_back(name[i]);

Don't assign.

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.