C++:关于string转C-风格字符串

时间:2023-01-04 17:34:20


std::basic_string::c_str

 C++ Strings library std::basic_string 
const CharT* c_str() const;    
     

Returns a pointer to a null-terminated character array with data equivalent to those stored in the string.

The pointer is such that the range [c_str(); c_str() + size()] is valid and the values in it correspond to the values stored in the string with an additional null character after the last position.

The pointer obtained from c_str() may be invalidated by:

Writing to the character array accessed through c_str() is undefined behavior.

c_str() and data() perform the same function. (since C++11)


这里:

用c_str() 方法可以返回一个指向C-风格的字符串的指针。

如:

string filename;
cout << "Enter the file name: ":
cin >> filename;
ofstream fout;
fout.open(filename.c_str());