.c_str() returns a const char*. If you need a mutable version, you will need to produce a copy yourself.
I know you can turn a C++ string into a const char array with .c_str(), but how do I turn a char array into a string?
Just use the constructor:
char cstring[] = "Some string";
std::string cppstring(cstring);
std::string this_also_works = cstring;
FWIW, as far as I know you're slightly misunderstanding the std::string::c_str() method.
It does not turn the C++ string into a const char array, but rather returns a pointer to the C++ string's char array.
To convert a C++ string to a char array, try:
std::string s("test");
const int Len = s.length();
char cs[Len];
snprintf(cs, Len, "%s", s.c_str());
It's late and that's off the top of my head, and the are many different ways to do it, but that more closely resembles your statement of turning a C++ string into a c string bc now you've literally got a c string that matches the data of the C++ string.
.c_str() returns a const char*. If you need a mutable version, you will need to produce a copy yourself.
vector<char> toVector( const std::string& s ) {
vector<char> v(s.size()+1);
std::memcpy( &v.front(), s.c_str(), s.size() + 1 );
return v;
}
vector<char> v = toVector("apple");
// what you were looking for (mutable)
char* c = v.data();
.c_str() works for immutable. The vector will manage the memory for you.
converting c style string to c++ style string - Stack Overflow
arduino ide - Convert C string to C++ string - Arduino Stack Exchange
C++ experts - implicit conversion of String to C-string?
c++ - Using c.str to convert from string to cstring - Stack Overflow
Videos
C++ strings have a constructor that lets you construct a std::string directly from a C-style string:
const char* myStr = "This is a C string!";
std::string myCppString = myStr;
Or, alternatively:
std::string myCppString = "This is a C string!";
As @TrevorHickey notes in the comments, be careful to make sure that the pointer you're initializing the std::string with isn't a null pointer. If it is, the above code leads to undefined behavior. Then again, if you have a null pointer, one could argue that you don't even have a string at all. :-)
Check the different constructors of the string class: documentation You maybe interested in:
//string(char* s)
std::string str(cstring);
And:
//string(char* s, size_t n)
std::string str(cstring, len_str);
std::string can take a char * as a constructor parameter, and via a number of operators.
char * mystr = "asdf";
std::string mycppstr(mystr);
or for the language lawyers
const char * mystr = "asdf";
std::string mycppstr(mystr);
char* cstr = //... some allocated C string
std::string str(cstr);
The contents of cstr will be copied to str.
This can be used in operations too like:
std::string concat = somestr + std::string(cstr);
Where somestr is already `std::string``
The problem is that str.c_str() returns a const char*, and you are trying to pass it to a char*. Use strcpy to get your expected result:
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
int main()
{
string str = "StackOverFlow";
char inCstring[20];
strcpy(inCstring, str.c_str());
cout << "str: " << str << endl;
cout << "inCstring: " << inCstring << endl;
return 0;
}
So I have figured out two ways to accomplish this.
First, it is important to remember that you can't assign to a whole array, meaning it is necessary to specify the element of the array to assign to. Attempting to assign a string to char array simply will not work for this reason.
That being said, by specifying the element it would be possible to assign a character in a specific element of a char array.
Below are two methods that accomplish a string to cstring(string to char array) "conversion". Please see answer by Vincent for complete code. I have found Method B better since I would like to have max size on my character array.
Method A:
string str = "StackOverFlow";
const char* inCstring;
inCstring = str.c_str();
Method B:
string str = "StackOverFlow";
char inCstring[20]{};
Then use strcpy
strcpy(inCstring, str.c_str());
1) How do I convert std::string to a C-style string?
Simply call string.c_str() to get a char const*. If you need a mutable _C-style_ string then make a copy. The returned C string will be valid as long as you don't call any non-const function of string.
2) Is there a way to get a C-style string from a stringstream?
There is, simply strstream.str().c_str(). The returned C string will be valid only until the end of the expression that contains it, that means that is valid to use it as a function argument but not to be stored in a variable for later access.
3) Is there a way to use a C-style string directly (without using stringstreams) to construct a string with an integer variable in it?
There is the C way, using sprintf and the like.
You got halfway there. You need foo.str().c_str();
your_string.c-str()-- but this doesn't really convert, it just gives you a pointer to a buffer that (temporarily) holds the same content as the string.- Yes, above,
foo.str().c_str(). - Yes, but you're generally better off avoiding such things. You'd basically be in the "real programmers can write C in any language" trap.
You can use sprintf to do it, or maybe snprintf if you have it:
char str[ENOUGH];
sprintf(str, "%d", 42);
Where the number of characters (plus terminating char) in the str can be calculated using:
(int)((ceil(log10(num))+1)*sizeof(char))
As pointed out in a comment, itoa() is not a standard, so better use the sprintf() approach suggested in the rival answer!
You can use the itoa() function to convert your integer value to a string.
Here is an example:
int num = 321;
char snum[5];
// Convert 123 to string [buf]
itoa(num, snum, 10);
// Print our string
printf("%s\n", snum);
If you want to output your structure into a file there isn't any need to convert any value beforehand. You can just use the printf format specification to indicate how to output your values and use any of the operators from printf family to output your data.
To answer the question without reading too much else into it I would
Copychar str[2] = "\0"; /* gives {\0, \0} */
str[0] = fgetc(fp);
You could use the second line in a loop with whatever other string operations you want to keep using chars as strings.
You could do many of the given answers, but if you just want to do it to be able to use it with strcpy, then you could do the following:
Copy...
strcpy( ... , (char[2]) { (char) c, '\0' } );
...
The (char[2]) { (char) c, '\0' } part will temporarily generate null-terminated string out of a character c.
This way you could avoid creating new variables for something that you already have in your hands, provided that you'll only need that single-character string just once.
New to cpp. Is it inefficient to convert std::string to c string for a library that only accepts c strings? Let me know if this is a dumb question.