std::string-কে C-স্টাইল স্ট্রিং-এ কনভার্ট করার দুটি পদ্ধতি।
পদ্ধতি ১: const char* (c_str())
#include <iostream>
using namespace std;
int main() {
string x("hello");
const char* ccx = x.c_str();
cout << ccx;
}
আউটপুট
hello
c_str() null-terminated const char* রিটার্ন করে। পয়েন্টারটি স্ট্রিং অবজেক্টের লাইফটাইম পর্যন্ত বৈধ থাকে।
পদ্ধতি ২: char* (copy() ব্যবহার করে)
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
string x("hello");
char* ccx = new char[x.length() + 1];
copy(x.begin(), x.end(), ccx);
ccx[x.length()] = '\0'; // null-terminate
cout << ccx;
delete[] ccx; // মেমরি মুক্ত করা জরুরি
}
আউটপুট
hello
সতর্কতা: ম্যালোকেটেড মেমরি delete[] দিয়ে মুক্ত করতে ভুলবেন না। C++17-এ string::data() non-const রিটার্ন করে (mutable), কিন্তু সেটিও নাল-টার্মিনেটেড নাও হতে পারে।