Reputation: 63
After writing the content of the text file to the TStringList object, I try to change one character in the line and then write the entire content of the object back to the file. In the saved file, the changed line character was not saved as expected and is still unchanged. To write the change of character to the file I need to use the String object.
void __fastcall TForm1::Button1Click(TObject *Sender)
{
TStringList *Lista = new TStringList;
if(OpenDialog1->Execute())
Lista->LoadFromFile(OpenDialog1->FileName);
Lista->Strings[0][1] = '0'; // this does not work
// Only this way work
String A = Lista->Strings[0];
A[1] = '0';
Lista->Strings[0] = A;
}
I don't understand why the sign change directly in the TStringList object doesn't happen, or if it does, why isn't it written to the file.
Upvotes: 0
Views: 87
Reputation: 596437
The TStringList::Strings[]
property getter DOES NOT return a reference to a String
object, like you are expecting. It returns a String
object by value instead, which means a copy is returned as a temporary object.
Strings[0][1] = ...
has no effect because you are modifying that temporary object and not assigning it anywhere afterwards, so it just goes out of scope immediately.
That is why you need to save that temporary object to a local variable first, and then assign that variable back to the Strings[]
property after modifying the variable's data.
Upvotes: 2