How to convert a string to char[] [duplicate]

2019-09-21 04:32发布

问题:

Possible Duplicate:
Convert std::string to const char* or char*

i've got a line from a txt data with this methode

 for ( int anrede=0;!user1.eof();anrede++){
     if (anrede==1){
         getline(user1, inhalt_anrede);       
     }
 }

now inhalt_anrede should be converted to char[5] anrede i have used anrede in other parts of the program.

so the txt data works like a save-data.

i'm still learning so please be tender ;D.

btw.: no, this is no homework like someone says about a other question from me. i from germany and in germany there is no C++ @ schools. not even java or delphi. if ur lucky u learn HTML, thats it.

回答1:

std::string str("abc");
char cstr[5];
strcpy(cstr, str.c_str());

Be sure not to overflow the c string (can contain only 4 chars + NULL in this example).



回答2:

You may want to look at the c_str() method of the string. For more information look here http://cplusplus.com/reference/string/string/c_str/



回答3:

Strings have a c_str() method that returns a char*. If you need it to be a char[5], then copy the first five characters from the string to one.

 char strArr[5];
 for (int i = 0; i < 5 && i < inhalt_anrede.length(); ++i) {
     strArr[i] = inhalt_anrede[i];
 }

Keep in mind that strArr isn't necessarily '\0' terminated now.



回答4:

Use c_str() member of std::string and memcpy:

char anrede[5];
if (anrede.size() >= 5)
    memcpy(anrede, inhalt_anrede.c_str(), 5);
else
    throw "string is too short";

Note that you use a variable called anrede already as counter in your for loop!



标签: c++ string char