char* to string conversion
Might be a common question, but google didn't come up with too much on this. If I'm reading characters from the command line, is there an easy way to convert the characters to a STL string?
Thanks
std::string takes a char* as an argument to one of it's constructors:
http://www.sgi.com/tech/stl/basic_string.html
ex:
I believe that the only requirements are that the char* passed to the constructor is NULL terminated (i.e. ends with a '\0' character).
-me
http://www.sgi.com/tech/stl/basic_string.html
ex:
char *charString = myFunctionToReadInput();std::string stlString(charString);
I believe that the only requirements are that the char* passed to the constructor is NULL terminated (i.e. ends with a '\0' character).
-me
You can read directly into a string:
EDIT: ah commandline, thought the OP was asking about input from the console.
std::string myInput;std::cin >> myInput;
EDIT: ah commandline, thought the OP was asking about input from the console.
Quote:Original post by matrisking
Might be a common question, but google didn't come up with too much on this. If I'm reading characters from the command line, is there an easy way to convert the characters to a STL string?
Thanks
Std::string takes care of char*s without even telling you:
int main(int argc, char **argv) { std::vector<std::string> args; for (unsigned i = 0; i < argc; i++) args.push_back(std::string(argv));}
Edit: B-B-B-BEATEN to the POST Post Post Post Post
If you want to convert them all at once:
std::string program_name = argv[0];
If you want to convert them all at once:
std::vector< std::string > args( argv , argv + arc );std::cout << "Program: " << args[0] << std::endl;if ( args.size() > 1 ) { std::cout << "First argument: " << args[1] << std::endl; std::cout << "First argument length: " << args[1].size() << endl;}
heh, try this out... :)
EDIT: Damn, i'm slow... :)
#include <string>#include <iostream>int main () { char *buf = "C style string"; std::string str1 (buf); // copy constructor std::string str2 = buf; // assignement operator std::cout << "buf = " << buf << std::endl; std::cout << "str1 = " << str1 << std::endl; std::cout << "str2 = " << str2 << std::endl; return 0;}
EDIT: Damn, i'm slow... :)
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement