简体   繁体   中英

How to assign a string to char *pw in c++

How to assign a string to char *pw in c++

like...

char *pw = some string

??

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

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 .

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>

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,

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM