Delphi XE3 - Can't concatenate strings
Asked Answered
Y

1

5

For the life of me, I cannot concatenate two(/three) strings. These are some codes I have tried:

dir := 'C:\Users\' + Username + '\Downloads\done.txt'; //"Username" is the computer's current username.
//another example vvv
dir := 'C:\Users\' + Username;
dir := dir + '\Downloads\done.txt';
//last example vvv
dir := Concat('C:\Users\', Username, '\Downloads\done.txt');

All of the examples always return the same result:

C:\Users\-username-

Never:

C:\Users\-username-\Downloads\done.txt

What am I doing wrong here?

Yezd answered 21/1, 2013 at 18:19 Comment(1)
Delphi string concatenation works. The code you present does not give the output you say. Present a full program to reproduce behaviour.Draftsman
M
16

My guess is that your Username variable contains #0 at its end and you're outputing that variable to a certain Windows API function. For instance the following code will result to this misbehavior:

procedure TForm1.Button1Click(Sender: TObject);
var
  Dir: string;
  Username: string;
begin
  Username := 'Username' + #0;
  Dir := Concat('C:\Users\', Username, '\Downloads\done.txt');
  ShowMessage(Dir);
end;

My suggestion is to check the value of your Username variable and remove the extra #0 at the end if there's some.

Mellow answered 21/1, 2013 at 18:26 Comment(4)
Thanks, it was a null termination character at the end of it. I will accept this as the answer when I can(2 minutes).Yezd
.. or let the RTL remove it Concat('C:\Users\', PChar(Username), ...);Globigerina
@Sertac, I haven't suggested how to remove that null terminator though, but PChar typecasting works well. Thanks for the tip!Mellow
A better option would be to find out why Username contains an erroneous #0 character in the first place and that fix that logic instead.Themis

© 2022 - 2024 — McMap. All rights reserved.