tarunmali
tarunmali

Reputation: 45

Why copy method of std::string in C++ is showing weird behavior in this program?

#include<iostream>
using namespace std;
int main() 
{
    string str1 = "geeksforgeeks is for geeks";   
    string str2 = "geeksforgeeks is for geeks";

    char ch1[100];
    char ch2[100];
 
    cout<<str1.size()<< endl << endl;
    str1.copy(ch1,23,0);
    str2.copy(ch2,24,0);
    
 
    cout << ch1 << endl << endl;
    cout << ch2 << endl << endl;
    


    return 0;

}

The length of string is 26, when I tried to copy more than 23 characters, it is showing weird behavior (printing random character in the last) Here is the output of the above program

26

geeksforgeeks is for ge

geeksforgeeks is for gee£qí╜∙⌂

Upvotes: 2

Views: 249

Answers (3)

Pratap Alok Raj
Pratap Alok Raj

Reputation: 1206

It's because you haven't set any '\0' (null) character to determine the end. That's why it's picking up garbage value.

you can do

#include<iostream>
using namespace std;
int main() 
{
    string str1 = "geeksforgeeks is for geeks";   
    string str2 = "geeksforgeeks is for geeks";

    char ch1[100];
    char ch2[100];
 
    cout<<str1.size()<< endl << endl;
    str1.copy(ch1,23,0);
    str2.copy(ch2,24,0);
    
    ch1[23] = '\0';  
    ch2[24] = '\0';  
 
    cout << ch1 << endl << endl;
    cout << ch2 << endl << endl;
    


    return 0;

}

Upvotes: 3

songyuanyao
songyuanyao

Reputation: 172864

You need to add null-terminator char by yourself; while std::string::copy doesn't do that.

E.g.

str1.copy(ch1,23,0);
ch1[23] = '\0';
str2.copy(ch2,24,0);
ch2[24] = '\0';

Upvotes: 2

Ted Lyngmo
Ted Lyngmo

Reputation: 117178

It's because your char[]'s are uninitialized and you don't place a \0 at the end of the strings after the copy.

Another solution is to initialize the char[]'s at construction:

char ch1[100]{};
char ch2[100]{};

Upvotes: 2

Related Questions