How to convert string to char array in C++

5 Answers

0 votes
#include <iostream>
 
int main() {
    std::string s = "C++ is a general-purpose programming language";
     
    auto char_string = s.c_str();
 
    std::cout << char_string;
}
 
 
 
 
/*
run:
 
C++ is a general-purpose programming language
 
*/

 



answered May 10, 2021 by avibootz
edited Apr 11, 2024 by avibootz
0 votes
#include <iostream>
#include <cstring>
 
int main() {
    std::string s = "C++ is a general-purpose programming language";
     
    char *p = new char[s.length() + 1];
    memmove(p, s.c_str(), s.length());
 
    std::cout << p;
     
    delete [] p;
}
 
 
 
 
/*
run:
 
C++ is a general-purpose programming language
 
*/

 



answered May 10, 2021 by avibootz
edited Apr 11, 2024 by avibootz
0 votes
#include <iostream>
#include <iterator>
#include <vector>
 
int main() {
    std::string s = "C++ is a general-purpose programming language";
     
    std::vector<char> v(s.begin(), s.end());
     
    std::copy(v.begin(), v.end(), std::ostream_iterator<char>(std::cout, ""));
}
 
 
 
 
/*
run:
 
C++ is a general-purpose programming language
 
*/

 



answered May 10, 2021 by avibootz
edited Apr 11, 2024 by avibootz
0 votes
#include <iostream>
#include <cstring>

int main()
{
    std::string s = "c c++ java php"; 
 
    char *p = new char [s.length() + 1];
    strcpy (p, s.c_str());
      
    for (int i = 0; i < s.length(); i++) { 
        std::cout << p[i] << "\n";
    } 
     
    delete p;
}




/*
run:
 
c
 
c
+
+
 
j
a
v
a
 
p
h
p
 
*/

 



answered Apr 11, 2024 by avibootz
0 votes
#include <iostream>
#include <cstring>

int main()
{
    std::string s = "c c++ java python"; 

    char *p = new char [s.length() + 1];
    strncpy(p, s.c_str(), s.length() + 1);
      
    for (int i = 0; i < s.length(); i++) { 
        std::cout << p[i] << "\n";
    } 
     
    delete p;
}




/*
run:
 
c
 
c
+
+
 
j
a
v
a
 
p
y
t
h
o
n
 
*/

 



answered Apr 11, 2024 by avibootz

Related questions

1 answer 295 views
5 answers 537 views
537 views asked Aug 10, 2019 by avibootz
1 answer 216 views
1 answer 90 views
1 answer 167 views
1 answer 165 views
165 views asked Jun 20, 2021 by avibootz
3 answers 318 views
318 views asked May 16, 2021 by avibootz
...