How to convert char array to string in C++

5 Answers

0 votes
#include <iostream>

std::string convert_char_array_to_string(char *p, int len) { 
    std::string s = ""; 
      
    for (int i = 0; i < len; i++) { 
        s = s + p[i]; 
    } 
    
    return s; 
} 
    
int main() 
{ 
    char arr[] = { 'a', 'b', 'c', 'd' }; 
  
    int len = sizeof(arr) / sizeof(char); 
  
    std::string s = convert_char_array_to_string(arr, len); 
  
    std::cout << s;
}
  
     
     
     
/*
run:
     
abcd
     
*/

 



answered Aug 10, 2019 by avibootz
edited May 10, 2024 by avibootz
0 votes
#include <iostream>

std::string convert_char_array_to_string(char *p, int len) { 
    std::string s = ""; 
      
    for (int i = 0; i < len; i++) { 
        s = s + p[i]; 
    } 
    
    return s; 
} 
    
int main() 
{ 
    char arr[] = "c c++";
  
    int len = sizeof(arr) / sizeof(char); 
  
    std::string s = convert_char_array_to_string(arr, len - 1); 
  
    std::cout << s;
}

     
     
     
/*
run:
     
c c++
     
*/

 



answered Aug 10, 2019 by avibootz
edited May 10, 2024 by avibootz
0 votes
#include <iostream>
     
int main() 
{ 
    char arr[] = "c c++";
  
    std::string s(arr);
 
    std::cout << s;
}
  
     
     
     
/*
run:
     
c c++
     
*/

 

 



answered Aug 10, 2019 by avibootz
edited May 10, 2024 by avibootz
0 votes
#include <iostream>
     
int main() 
{ 
    char arr[] = { 'a', 'b', 'c', 'd', 'e' }; 
  
    std::string s = arr; 
 
    std::cout << s;

}
  
     
     
     
/*
run:
     
abcde
     
*/

 



answered Aug 10, 2019 by avibootz
edited May 10, 2024 by avibootz
0 votes
#include <iostream>
 
int main()
{
    char arr[] = {'c', '+', '+'}; 
     
    std::string s = std::string(arr);
     
    std::cout << s;
}
 
 
 
   
/*
run:
   
c++
  
*/

 



answered May 10, 2024 by avibootz

Related questions

1 answer 295 views
5 answers 550 views
550 views asked May 10, 2021 by avibootz
1 answer 216 views
1 answer 91 views
1 answer 167 views
1 answer 166 views
166 views asked Jun 20, 2021 by avibootz
3 answers 318 views
318 views asked May 16, 2021 by avibootz
...