samedi 15 janvier 2022

Getting Extra characters at the end when Creating std::string from char*

I have just started learning C++. Now i am learning about arrays. So i am trying out different examples. One such example is given below:

int main()
{
    const char *ptr1 = "Anya";
    char arr[] = {'A','n','y','a'};
    
    std::string name1(ptr1); //this works 
    std::cout << name1 << std::endl;
    
    std::string name2(arr); 
    std::cout << name2 << std::endl; //this prints extra characters at the end?
    return 0;
}

In the above example at the last cout statement i am getting some extra characters at the end. My question is that how can i prevent this from happening in the above code and what is wrong with the code so that i don't make the same mistake in future?

Aucun commentaire:

Enregistrer un commentaire