Jump to content
  • Advertisement
Sign in to follow this  

char* to string conversion

This topic is 4411 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post


Link to post
Share on other sites
Advertisement
You can read directly into a string:


std::string myInput;
std::cin >> myInput;


EDIT: ah commandline, thought the OP was asking about input from the console.

Share this post


Link to post
Share on other sites
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));
}

Share this post


Link to post
Share on other sites
Edit: B-B-B-BEATEN to the POST Post Post Post Post

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

Share this post


Link to post
Share on other sites
heh, try this out... :)

#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... :)

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!