140

I would like to convert string to char array but not char*. I know how to convert string to char* (by using malloc or the way I posted it in my code) - but that's not what I want. I simply want to convert string to char[size] array. Is it possible?

#include <iostream>
#include <string>
#include <stdio.h>
using namespace std;
int main()
{
 // char to string
 char tab[4];
 tab[0] = 'c';
 tab[1] = 'a';
 tab[2] = 't';
 tab[3] = '0円';
 string tmp(tab);
 cout << tmp << "\n";
 // string to char* - but thats not what I want
 char *c = const_cast<char*>(tmp.c_str());
 cout << c << "\n";
 //string to char
 char tab2[1024];
 // ?
 return 0;
}
Ziezi
6,4974 gold badges42 silver badges54 bronze badges
asked Nov 8, 2012 at 17:08
1

11 Answers 11

169

Simplest way I can think of doing it is:

string temp = "cat";
char tab2[1024];
strcpy(tab2, temp.c_str());

For safety, you might prefer:

string temp = "cat";
char tab2[1024];
strncpy(tab2, temp.c_str(), sizeof(tab2));
tab2[sizeof(tab2) - 1] = 0;

or could be in this fashion:

string temp = "cat";
char * tab2 = new char [temp.length()+1];
strcpy (tab2, temp.c_str());
G. Sliepen
8,0381 gold badge18 silver badges33 bronze badges
answered Nov 8, 2012 at 17:11
12
  • 11
    The catch with strncpy is that it won't null-terminate if it reaches the size before it finds a null in the source string. Gotta be careful with that too! Commented Nov 8, 2012 at 17:15
  • 1
    Yes, I think that's a reasonable way to handle it. Commented Nov 8, 2012 at 17:17
  • 1
    strncpy is for safety in that strncpy will not overrun the buffer you give it. Also strcpy_s is not in C99, but it has recently been added in C11. Commented Nov 8, 2012 at 17:36
  • 9
    I love the way people abuse the word safety... oh, there's not enough room for the string, so let's truncate it.. oh, we accidentally removed the info about the patient's life threatening drug allergy.. but we don't have a buffer overrun anymore. well, I guess it's safe... Commented May 15, 2015 at 14:06
  • 5
    @KarolyHorvath - safety in different domains. Obviously, you need to check your functional requirements and Not Do Stupid Things. But if you overrun the buffer you lose any guarantee of knowing what will happen. Correct coding ensures the program is "safe" to run on your OS. Correct thinking ensures the program is "safe" at doing what the user needs. Commented Jun 17, 2015 at 11:11
84

Ok, i am shocked that no one really gave a good answer, now my turn. There are two cases;

  1. A constant char array is good enough for you so you go with,

    const char *array = tmp.c_str();
    
  2. Or you need to modify the char array so constant is not ok, then just go with this

    char *array = &tmp[0];
    

Both of them are just assignment operations and most of the time that is just what you need, if you really need a new copy then follow other fellows answers.

answered Mar 5, 2015 at 7:55
5
  • 7
    He wants a char array, not a char * Commented Oct 8, 2015 at 0:02
  • 17
    The pointer he created is the same thing as a char array. An array variable in C and C++ is just a pointer to the first element in the array. Commented Jun 1, 2017 at 17:39
  • 5
    @JustinC.B. not really! array variables might decay into pointers but they are not same in C++. e.g. std::size(elem) in C++ is well defined when elem is a char array but it fails to compile when elem is a char* or const char*, you can see it at here Commented Jan 15, 2019 at 19:27
  • Will #2 cause problems (dangling pointer) if tmp is stack-allocated and goes out of scope but array has a longer lifetime? Commented Aug 27, 2021 at 1:14
  • @WilliamBradley yes, you will access invalid memory Commented Apr 5, 2022 at 10:46
20
str.copy(cstr, str.length()+1); // since C++11
cstr[str.copy(cstr, str.length())] = '0円'; // before C++11
cstr[str.copy(cstr, sizeof(cstr)-1)] = '0円'; // before C++11 (safe)

It's a better practice to avoid C in C++, so std::string::copy should be the choice instead of strcpy.

answered Dec 27, 2014 at 2:46
16

Easiest way to do it would be this

std::string myWord = "myWord";
char myArray[myWord.size()+1];//as 1 char space for null is also required
strcpy(myArray, myWord.c_str());
answered Jan 10, 2014 at 16:12
2
  • 20
    Array size must be a compile-time constant in C++. Commented Mar 16, 2014 at 10:17
  • 1
    @PhaniRithvij It's wrong unless you're only targeting a compiler that allows this as a language extension, in which case it's still bad practice. Commented Oct 11, 2020 at 16:20
6

Just copy the string into the array with strcpy.

answered Nov 8, 2012 at 17:11
5

Try this way it should be work.

string line="hello world";
char * data = new char[line.size() + 1];
copy(line.begin(), line.end(), data);
data[line.size()] = '0円'; 
answered Oct 19, 2015 at 11:47
4

Try strcpy(), but as Fred said, this is C++, not C

answered Nov 8, 2012 at 17:11
3

You could use strcpy(), like so:

strcpy(tab2, tmp.c_str());

Watch out for buffer overflow.

answered Nov 8, 2012 at 17:12
3

If you don't know the size of the string beforehand, you can dynamically allocate an array:

auto tab2 = std::make_unique<char[]>(temp.size() + 1);
std::strcpy(tab2.get(), temp.c_str());
answered Oct 10, 2015 at 8:55
1

If you're using C++11 or above, I'd suggest using std::snprintf over std::strcpy or std::strncpy because of its safety (i.e., you determine how many characters can be written to your buffer) and because it null-terminates the string for you (so you don't have to worry about it). It would be like this:

#include <string>
#include <cstdio>
std::string tmp = "cat";
char tab2[1024];
std::snprintf(tab2, sizeof(tab2), "%s", tmp.c_str());

In C++17, you have this alternative:

#include <string>
#include <cstdio>
#include <iterator>
std::string tmp = "cat";
char tab2[1024];
std::snprintf(tab2, std::size(tab2), "%s", tmp.c_str());
answered Aug 25, 2019 at 4:48
-1

Well I know this maybe rather dumb (削除) than (削除ここまで) and simple, but I think it should work:

string n;
cin>> n;
char b[200];
for (int i = 0; i < sizeof(n); i++)
{
 b[i] = n[i];
 cout<< b[i]<< " ";
}
tmthydvnprt
10.8k10 gold badges54 silver badges74 bronze badges
answered Apr 2, 2016 at 16:14
1
  • Well, not really. You're just assuming that n can't be larger than b. It would crash if n>b. Better to use the strcpy function already provided. Edit: At some cases it might be even better to use strcpy_s as it adds check for NULL pointers (if your platform supports it) Commented Sep 30, 2017 at 19:24

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.