0

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;
}
  • Size of array in C/C++ must be a compile time constant. You should allocate buffer dynamically or just use `std::vector`. – user7860670 Mar 10 '21 at 06:04
  • Your code to read from the file reads only one line. Is that your intention? – R Sahu Mar 10 '21 at 06:11
  • @user7860670 Nope. Size of array in C doesn't need to be compile time constant. This question is about C++ though. – eerorika Mar 10 '21 at 06:14
  • @eerorika Nouveau C dialects with (optional) VLA support are not C. – user7860670 Mar 10 '21 at 06:25
  • @user7860670 VLA support is not optional in C99. It may be optional in later C standards, but it is still standard C whether optional or not. – eerorika Mar 10 '21 at 06:28

1 Answers1

1

You cannot do this. The size of an array variable must be a compile time constant in C++.

You also don't need to do this. message already owns a dynamic null terminated array. There is no need to copy it elsewhere. If you need a copy of the string, then create another std::string object.

eerorika
  • 232,697
  • 12
  • 197
  • 326