0

I created a function to save a text file using <fstream>.

void save(AnsiString flName, AnsiString &YourText) {
  char saving[strlen(YourText.c_str())]; // << ERROR

  strncpy(saving, YourText.c_str(), sizeof(saving) - 1);

  ofstream ok(flName.c_str(), ios::out);
  ok << saving;
  ok.close();
}

I have problems in line 2. said: Constant expression required

can you help me. whether there are other more effective method to save a text file?

Error Person
  • 33
  • 1
  • 4
  • 1. Look up the documentation of `AnsiString`. Does `c_str()` return a `char`? 2. Look up the documentation of `strncpy`. Is the first parameter `char`? – juanchopanza Feb 05 '15 at 07:27
  • Closing the question because it emphasizes on the VLA. The last line should have been actually a different question. – iammilind Feb 05 '15 at 07:38

3 Answers3

1

The error is caused by trying to create an array, which needs a constant size.

In order to fix that, use a std::vector. However, in your case, use this:

ofstream out(flName.c_str());
out << YourText;

BTW: You need to read a C++ tutorial. Absolutely. Your code contains so many issues that it's hard to start, like multiple one-off errors, failure to use C-style strings (i.e. NUL-terminated strings) and lack of understanding of resource management in C++ in general. Also, you don't have any error handling in place. Const correctness.

Ulrich Eckhardt
  • 16,572
  • 3
  • 28
  • 55
0

You cannot initialize an array of dynamic size like that. You have to create it via dynamic allocation (e.g. malloc or new)

So you need:

void save(AnsiString flName, AnsiString &YourText) {
  char* saving = new char[strlen(YourText.c_str())];

  strncpy(saving, YourText.c_str(), sizeof(saving) - 1);

  ofstream ok(flName.c_str(), ios::out);
  ok << saving;
  delete[] saving;
  ok.close();
}

Stack allocations, need to know the size of what is being allocated at compile time. There is no way the compiler could know the length of YourText ahead of time.

This code could be dramatically simplified, but it is out of scope of this question. Feel free to start a chat if you would like some pointers on how to rewrite this.

Jonathan Henson
  • 8,076
  • 3
  • 28
  • 52
0

the size of an array should be a constant; You cannot initialize the size with a variable

Arun A S
  • 6,421
  • 4
  • 29
  • 43