Reputation: 8350
How to assign a string to a char*
(char pointer) in C++?
char *pw = some string
Upvotes: 6
Views: 29796
Reputation: 4887
For constant initialization you can simply use
const char *pw = "mypassword";
if the string is stored in a variable, and you need to make a copy of the string then you can use strcpy() function
char *pw = new char(strlen(myvariable) + 1);
strcpy(pw, myvariable);
// use of pw
delete [] pw; // do not forget to free allocated memory
Upvotes: 8
Reputation: 16640
I think you may want to do this:
using namespace std;
string someString;
geline(cin,someString);
char *pw = strdup(someString.c_str());
But consider doing it another way. Check out http://tiswww.case.edu/php/chet/readline/rltop.html (GNU Readline library). I don't know details about it, just heard about it. Others may have more detailed or other tips for reading passwords from standard input.
If you only want to use it for a single call for something you do not need to copy the contents of someString, you may use someString.c_str()
directly if it is required as const char *
.
You have to use free
on pw
some time later,
Upvotes: 3
Reputation: 8529
String must be enclosed in double quotes like :
char *pStr = "stackoverflow";
It will store this string literal in the read only memory of the program. And later on modification to it may cause UB.
Upvotes: 1
Reputation: 3891
If you just want to assign a string literal to pw
, you can do it like char *pw = "Hello world";
.
If you have a C++ std::string
object, the value of which you want to assign to pw
, you can do it like char *pw = some_string.c_str()
. However, the value that pw
points to will only be valid for the life time of some_string
.
Upvotes: 4
Reputation: 116714
If you mean a std::string
, you can get a pointer to a C-style string from it, by calling c_str
. But the pointer needs to be const
.
const char *pw = astr.c_str();
If pw
points to a buffer you've previously allocated, you might instead want to copy the contents of a string into that buffer:
astr.copy(pw, lengthOfBuffer);
If you're starting with a string literal, it's already a pointer:
const char *pw = "Hello, world".
Notice the const
again - string literals should not be modified, as they are compiled into your program.
But you'll have a better time generally if you use std::string
everywhere:
std::string astr("Hello, world");
By the way, you need to include the right header:
#include <string>
Upvotes: 3