Sign in to follow this  
Peter Conn

String/Char issues

Recommended Posts

Hiya I am having quite a fw problems using chars and string in my console applications. Naturally I use string for my class member. However std::cin.get seems only to get chars. Also I need to use a function that takes a "const char *". Could someone please tell me how to convert "char arrays" into strings, and how to convert strings into "const char *"s. "strcpy" and "strncpy" don't seem to work either. P.S. I'm working in C++.

Share this post


Link to post
Share on other sites

void func(const char*);
...
const char* str1 = "Hello World!";
char str2[] = "How's it going?";

std::string str3 = str1; // copies the contents of str1

str3 = str2; // copies the contents of str1, overwrites old contents of str3

std::cin >> str3; // reads one word into str3

std::getline(cin, str3); // reads a whole line into str3

func(str3.c_str()); // c_str() returns a const char* pointing to str3's contents

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