Its easy and intuitive to make a char array a string, but not the reverse.
#include <iostream>
int main() {
char chars[] = "Some Chars";
std::string s = chars; // could also just be "Some Chars";
std::cout << s;
return 0;
}
//Outputs: Some Chars
The above code sample looks nice and easy due to some operator overloading. If you don't know what operator overloading is and would like to learn more, please see the link to wikibooks, it has some decent coverage on the topic.
There is no similar overload for the char (or char array) types as these are not C++ objects. Because of this we have to look up the member function in the string object that returns a char array. The function in this case is c_str();. Follows is an example of its use.
int main() {
char chars[] = "Some Chars";
std::string s = chars; // could also just be "Some Chars";
std::cout << s << " from string object" << std::endl;
char returned_chars[10] = s.c_str();
std::cout << returned_chars << " from char array" << std::end;
return 0;
}
//Outputs:
//Some Chars from string object
//Some Chars from char array
Its really easy once you find what function to use. For more information about strings in general, have a look at this useful guide on the string object.
Also if anyone was curious, the std::cout object overrides the << symbol, which allows it to output text to your terminal.
No comments:
Post a Comment