Convert string to char in cpp

How to convert string to char array in C++?

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 #include #include 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.c_str()); cout 

11 Answers 11

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()); 

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!

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.

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.

Читайте также:  Access local file with javascript

@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.

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

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

const char *array = tmp.c_str(); 

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.

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.

@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

Will #2 cause problems (dangling pointer) if tmp is stack-allocated and goes out of scope but array has a longer lifetime?

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.

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()); 

@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.

Just copy the string into the array with strcpy .

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'; 

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

You could use strcpy() , like so:

Watch out for buffer overflow.

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

auto tab2 = std::make_unique(temp.size() + 1); std::strcpy(tab2.get(), temp.c_str()); 

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 #include std::string tmp = "cat"; char tab2[1024]; std::snprintf(tab2, sizeof(tab2), "%s", tmp.c_str()); 

In C++17, you have this alternative:

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

Источник

convert string to char* [duplicate]

@john: Maybe some people thought that this is a duplicate of another question, or they thought that this question shows no effort, I don't really know. For a beginner this isn't an obvious question, but I don't expect a comment from the downvoters in this case, since it's a duplicate.

@Zeta Maybe but the downvotes appeared before any indication of the duplication. Seems like bad manners to me.

2 Answers 2

There are many ways. Here are at least five:

/* * An example of converting std::string to (const)char* using five * different methods. Error checking is emitted for simplicity. * * Compile and run example (using gcc on Unix-like systems): * * $ g++ -Wall -pedantic -o test ./test.cpp * $ ./test * Original string (0x7fe3294039f8): hello * s1 (0x7fe3294039f8): hello * s2 (0x7fff5dce3a10): hello * s3 (0x7fe3294000e0): hello * s4 (0x7fe329403a00): hello * s5 (0x7fe329403a10): hello */ #include #include #include int main() < std::string s0; const char *s1; char *s2; char *s3; char *s4; char *s5; // This is the initial C++ string. s0 = "hello"; // Method #1: Just use "c_str()" method to obtain a pointer to a // null-terminated C string stored in std::string object. // Be careful though because when `s0` goes out of scope, s1 points // to a non-valid memory. s1 = s0.c_str(); // Method #2: Allocate memory on stack and copy the contents of the // original string. Keep in mind that once a current function returns, // the memory is invalidated. s2 = (char *)alloca(s0.size() + 1); memcpy(s2, s0.c_str(), s0.size() + 1); // Method #3: Allocate memory dynamically and copy the content of the // original string. The memory will be valid until you explicitly // release it using "free". Forgetting to release it results in memory // leak. s3 = (char *)malloc(s0.size() + 1); memcpy(s3, s0.c_str(), s0.size() + 1); // Method #4: Same as method #3, but using C++ new/delete operators. s4 = new char[s0.size() + 1]; memcpy(s4, s0.c_str(), s0.size() + 1); // Method #5: Same as 3 but a bit less efficient.. s5 = strdup(s0.c_str()); // Print those strings. printf("Original string (%p): %s\n", s0.c_str(), s0.c_str()); printf("s1 (%p): %s\n", s1, s1); printf("s2 (%p): %s\n", s2, s2); printf("s3 (%p): %s\n", s3, s3); printf("s4 (%p): %s\n", s4, s4); printf("s5 (%p): %s\n", s5, s5); // Release memory. free(s3); delete [] s4; free(s5); >

Источник

C++ How to convert string to char*

I need to convert a string to a char * for use in strtok_s and have been unable to figure it out. c_str() converts to a const char *, which is incompatible. Also, if someone could explain to me why the second strtok_s function (inside the loop) is necessary, it'd be a great help. Why do i need to explicitly advance the token rather than, for example, the while loop it is in, which fetches each line of a file consecutively, implicitly.

By the way, C++ strings can have NUL characters in the middle of them, since C++ defines strings in terms of some bytes and a length, rather than C's "sequence of bytes terminated with NUL". So if all you know about the input is that it's a C++ string, C functions like strtok actually don't work, because they might falsely detect what they think is the end of the string, before the actual end.

10 Answers 10

Use strdup() to copy the const char * returned by c_str() into a char * (remember to free() it afterwards)

Note that strdup() and free() are C, not C++, functions and you'd be better off using methods of std::string instead.

The second strtok_s() is needed because otherwise your loop won't terminate ( token 's value won't change).

but why do i need to explicitly advance the token rather than for example, the while loop it is in, which fetches each line of a file consecutively, implicitly?

Look at the code again: The first invocation of strtok() gets the first token from the line from the file. Then the while()'s condition checks if token is NULL. If it's not, the printf() is executed, and the next token is extracted. What confuses you is probably the fact that the variable next_token does not in fact store the next token, but rather the remainder of the line. That's just the way strtok_s() works.

You can't convert to a char * because that would that would allow you to write to std::string 's internal buffer. To avoid making std::string 's implementation visible, this isn't allowed.

Instead of strtok , try a more "C++-like" way of tokenizing strings. See this question:

It is impossible. The reason is that in object-oriented programming, objects don't like external clients accessing their internal representation directly. See en.wikipedia.org/wiki/Information_hiding

You'll just have to believe it. The cast from const to non-const pointer is possible, but attempting to modify the data pointed to has undefined behavior. c_str() is not required to return the string's internal buffer - it could copy the string out to a new location and show you that. Obviously modifying any such clone of the original string would not work. In C++0x, the implementation of string is more tightly controlled, and IIRC you will be able to use &line[0] as a char* pointing to the string data. Although that might not be NUL-terminated.

As Daniel said, you could go with

Which is better then the strcpy I originally proposed since it allocates the necessary space

It may give deprecation warnings in VC++. It is deprecated by Microsoft for reasons of security (which makes their OS look bad), it is not deprecated from the ISO standard library. The warning message also tells you how to fix it (it suggests two ways).

strtok() is a badly designed function to begin with. Check your documentation to see if you have a better one. BTW, never use strtok() in any sort of threaded environment unless your docs specifically say it's safe, since it stores state in between calls and modifies the string it's called on. I assume strtok_s() is a safer version, but it's not going to be a really safe one.

To convert a std::string into the char * , you can do:

char * temp_line = new char[line.size() + 1]; // +1 char for '\0' terminator strcpy(temp_line, line.c_str()); 

and use temp_line . Your installation may have a strdup() function, which will duplicate the above.

The reason you need two calls to strtok_s() is that they do different things. The first one tells strtok_s() what string it needs to work on, and the second one continues with the same string. That's the reason for the NULL argument; it tells strtok_s() to keep going with the original string.

Therefore, you need one call to get the first token, and then one for each subsequent token. They could be combined with something like

char * temp_string_pointer = temp_line; while ((token = strtok_s( con, "#", &next_token)) != NULL) < temp_string_pointer = NULL; 

and so on, since that would call strtok_s() once with the string pointer and after that with NULL . Don't use temp_line for this, since you want to delete[] temp_line; after processing.

You may think this is a lot of fiddling around, but that's what strtok() and relatives usually entail.

Источник

Оцените статью