Sign in to follow this  
matrisking

char* to string conversion

Recommended Posts

matrisking    282
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
97    138
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
nullsquared    126
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[i]));
}

Share this post


Link to post
Share on other sites
MaulingMonkey    1730
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this