Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to store a char array (or part of it) into const char*?

I’m new to C++, and I’m having trouble to concatenate a const char* with a char aray.  

First, I’d like to ask a question: Is const char* the same as std::string?

And going straight to my problem, this is what I’m trying:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I have this 10 sized char array that contains letters from a to j:

char my_array[10] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', j};

And I want to store this array (or part of it), using a const char*. But I could not do the concatenation, I thought it would be some think like this:

    const char* group_of_letters = "\0";
    
    for(int i = 0; i <= 9; i++){
        group_of_letters += my_array[i];
    }

I’d like to use the for loop because I’ll need it on my real project to store defined intervals of that array into the const char*
But it didn’t work any way that I have tried.

If it helps, my complete code would look like this:

#include <iostream>

int main(){
    
    char my_array[10] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'};
    const char* group_of_letters = "\0";
    
    for(int i = 0; i <= 9; i++){
        group_of_letters += my_array[i];
    }
    
    std::cout << group_of_letters;
    
    return 0;
}

->Using Dev C++ 5.11 – 06/08/2023

>Solution :

First, I’d like to ask a question: Is const char* the same as std::string?

No they are not the same, const char* is a pointer to a character sequence in C-style strings, while std::string is a C++ class that manages and manipulates strings with automatic memory management.

You can’t concatenate a char* array using the + operator.

In you case it’s better to use std::string as below :

#include <iostream>
#include <string>

int main(){
    
    char my_array[10] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'};
    std::string group_of_letters;
    
    for(int i = 0; i <= 9; i++){
        group_of_letters += my_array[i];
    }
    
    std::cout << group_of_letters << std::endl;
    
    return 0;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading