How can I convert a string to char[200]?
This is a discussion on Convert string to char[200] within the C++ Programming forums, part of the General Programming Boards category; How can I convert a string to char[200]?...
How can I convert a string to char[200]?
Use the std::string c_str() member, to return a char*. More info:
http://www.msoe.edu/eecs/cese/resources/stl/string.htm
http://www.cppreference.com/cppstring/c_str.html
You should always check the reference pages.
Heres a post found about it using google, fourth on the list when searching: string to char c++
http://66.102.7.104/search?q=cache:n...+c%2B%2B&hl=en
The poster gives his version to convert it saying x line isnt working, then at the bottom of the page someone gives the solution line.
Warning: Have doubt in anything I post.
GCC 4.5, Boost 1.40, Code::Blocks 8.02, Ubuntu 9.10 010001000110000101100101
Why do you think you need to convert a string to char[200]? There's a good chance you don't.
You you specifically want an array as in char x[200]; to be filled, you can use the std::copy subroutine provided by the <algorithm> header. E.g.
This code makes sure that no more than 199 elements are copied, leaving room for the null terminator and assigning it. You should only use c_str() if you intend on only using the returned read-only char* before your next non-const member function on s -- so that makes it only good for short-term use, like functions or methods that expect char*s. You could use strncpy on the c_str, but that's no better than std::copy. In fact, it might be worse because at least one implementation of c_str() that I vaguely remember reading about copies the contents of the string into a separate buffer.Code:#include <algorithm> #include <string> int main() { std::string s("Hello!"); char x[200]; *(std::copy(s.begin(), s.end() - s.begin() < 200 ? s.end() : s.begin() + 199, x)) = 0; }
Last edited by Rashakil Fol; 08-22-2005 at 01:20 PM.