How to convert std::string to const char* or char* in C++?
Hello everyone! I just started learning C++ and encountered a problem when working with strings. I have a variable of type `std::string`, and I need to pass it to a function that expects `const char*` or `char*`. For example, I'm trying to open a file using the `fopen()` function, but it doesn't accept `std::string`. Here's my code:
```cpp
#include
#include
#include
int main() {
std::string filename = "data.txt";
FILE* file = fopen(filename, "r"); // Compilation error!
if (file) {
std::cout << "File opened successfully" << std::endl;
fclose(file);
}
return 0;
}
```
The compiler gives an error: `cannot convert 'std::string' to 'const char*'`. I understand that `std::string` and `const char*` are different types, but how do I convert them?