I'm trying read a text file using fstream and then convert the string into an array of characters. However, when I create an integer "n" that's the size of the string plus 1, I can't use that to initialize the size of the array. I get a message saying, "The expression must have a constant value." The text file I'm trying to read just says, "This is a message". Which is 17 characters long. When I enter the number 18, (char messageArray[18]), everything works fine. But I'd like to be able to pass a value based off of whatever length my text message is.
#include <iostream>
#include <fstream>
#include <cstring>
#include <string>
using namespace std;
int main() {
// Read the message text file and save it to a string
fstream newfile;
string message;
newfile.open("input.txt", ios::in);
if (newfile.is_open()) {
getline(newfile, message);
newfile.close();
}
// Convert the message string to an array of characters
int n{};
n = message.size() + 1;
char messageArray[n];
strcpy_s(messageArray, message.c_str());
cout << messageArray << endl;
return 0;
}