sprintf issue

//C++ Builder XE7 

Edit1->Text = "Cavalieri";

AnsiString URL = "xyz.com?Name=";
AnsiString Name = Edit1->Text;

AnsiString  s1;
s1.sprintf("%s%s", URL, Edit1->Text);

AnsiString s2;
s2.sprintf("%s%s", URL, Name);

At this point:
s1 = "xyz.com?Name=C";
s2 = "xyz.com?Name=Cavalieri";


Why can't I embed a TEdit directly in a sprintf statement?  I'm sure it's a Unicode issue.

7/1/2015 5:19:10 PM
embarcadero.cppbuilder.using 1848 articles. 1 followers. Follow

2 Replies

Similar Articles

[PageSpeed] 33
Get it on Google Play
Get it on Apple App Store

Doug wrote:

> AnsiString  s1;
> s1.sprintf("%s%s", URL, Edit1->Text);

That will not work as shown.  In CB2009+, Edit1->Text is a UnicodeString, 
not an AnsiString.  The AnsiString::sprintf() method expects a char* for 
its "%s" format specifier, but UnicodeString is based on wchar_t* instead, 
so you need to use "%ls" instead of "%s" for wchar_t* input to AnsiString::sprintf(). 
 Also, you need to use the (Ansi|Unicode)String::c_str() method to get the 
actual pointer to the character data, do not pass (Ansi|Unicode)String objects 

AnsiString  s1;
s1.sprintf("%s%ls", URL.c_str(), Edit1->Text.c_str());

> AnsiString s2;
> s2.sprintf("%s%s", URL, Name);

This work, only because the Ansi "%s" specifer expects char* and AnsiString 
is based on char*.  But again, use the c_str() method, at least:

AnsiString s2;
s2.sprintf("%s%s", URL.c_str(), Name.c_str());

> At this point:
> s1 = "xyz.com?Name=C";

Yes, because you passed a wchar_t* where a char* was expected, so the data 
was interpretted as a null-terminated Ansi string and the second byte in 
the wchar_t* data was a null.

> Why can't I embed a TEdit directly in a sprintf statement?

You can, you are just doing it the wrong way.  Not only because of the Ansi/Unicode 
issue of sprintf(), but also because you are not even encoding the URL's 
parameter data correctly anyway.  Reserved characters and Unicode characters 
need to be charset-encoded (typically to UTF-8) and then url-encoded in "%XX" 

You need to do something more like this:

AnsiString UrlParamEncode(const UTF8String &Value)
    AnsiString ret;
    for (int i = 1; i <= Value.Length();)
        char c = Value[i];
        if (c <= 0x7F)
            if (((c >= 'A') && (c <= 'Z')) ||
                ((c >= 'a') && (c <= 'z')) ||
                ((c >= '0') && (c <= '9')))
                ret += c;
                ret.cat_sprintf("%%%02X", c);
            int len;
            if ((c & 0xE0) == 0xC0)
                len = 2;
            else if ((c & 0xF0) == 0xE0)
                len = 3;
                len = 4;
            for (int j = 0; j < len; ++j)
                ret.cat_sprintf("%%%02X", Value[i+j]);
            i += len;

AnsiString s1 = URL + UrlParamEncode(Edit1->Text);

Or, using Indy, which ships pre-installed in the IDE, you can use its TIdURI 
class to encode URLs, eg:

#include <IdURI.hpp>

AnsiString s1 = URL + TIdURI::ParamsEncode(Edit1->Text);


#include <IdURI.hpp>

AnsiString s1 = TIdURI::URLEncode(URL + Edit1->Text);

Remy Lebeau (TeamB)
7/1/2015 6:13:47 PM
Thank you for the nice answer!

7/15/2015 4:55:26 AM

Similar Artilces:

Issues in using reporting services we are using vs2005 and adding reports "*.rdlc", and are facing with follwoing issues
1:-There is one Main report having 2 subreports in it, each sub reoprt has it own header and footer but when its called from Master report, the header and footer of the sub report doesnt show on the Master report, how to make them visible. 2:-If we need to add some customize code for the report, we used the CustomCode tab that appear when Properties link of that report is clicked, how can we acess the items on the report under that code ???like if the report has the subreports, tables and want to acess their visibility is there any way.?? 3:-How can we check in the cutomcode o...

Issues with using a record type and using getmem
I have a record type defined. There are several fields, and I want to assign to them from a custom class: (D2010, win7) <code> type tmyrec record field1: pchar; ... end; type tmyclass = class ffield1: string; public property field1: string read ffield1 write ffield1; procedure assignto(var aMyRec: tmyrec); procedure freeMem(var aMyRec: tmyrec); end; ... procedure tmyclass.assignto(var aMyRec: tmyrec); begin if not assigned(aMyRec.field1) then getmem(aMyRec.field1,4); aMyRec.field1 := pchar(self.field1); end; ...

Connection issue with Sybase using Studio 2003 using GUI
When I use Server Explorer in studio 2003 the connection fails , and also get some errors. 1.. I used Sybase ADO Provider, when the Data Link properties comes I am able to the test connection successfully, once I have the connection when I click on the tables , Procedures etc I get the Connection Failure Error. So I cannot do any thing with this connection. 2.. I used Sybase ASE OLE DB Provider in the Data Link properties same as above successful connection, the tables expand and procedure come up(I can see all the objects) when I try to drag and drop a t...

Using Using
I have just completed reading a chapter in my book on performance. The books says to speed up performance on your web site you should use the using statement when opening connections. My question is how do you catch errors if you are using this as apposed to a try catch block.thanksBryan  Why would you use it as an alternative to a try/catch statement. Couldn't you just do something like  public void UsingSomeMethod() { try { SomeMethod(); } catch(SomeException e) { /// do something useful }}public void SomeMethod() { using (Something) { ...

Cross platform compatability using issue using oledb connection
I am writing a website application that needs to connect to either Oracle or MSSQL Server depending on what the client wants. Given this issue I am writing all my sql statements using the ANSI 92 standards and using the oledb connect as it is capable of handling this. It is all going well however I have hit a problem with string concatanation in the sleect statement. in oracle I would do this - select firstname || ' ' || Middlename || ' ' || lastname as fullname from whatevertablein mssql I would do this - select firstname + ' ' + Middlename + ' &...

When to use ( and when to use ((?
I'm just not getting it. When do you use ( in a statement, when do you need to use ((, and is the space after either or both mandatory? For example, I coded this statement: if (( $_ eq $bad_guys_ip )) { more_stuff_here }; Why the two (( in an if? And why does it seem to not work when I miss the space after the ((? Thanx! Mark me as... /Corn-fused|Dense/ > I'm just not getting it. >=20 > When do you use ( in a statement, when do you need to use ((, and is > the space after either or both mandatory? >=20 > For example, I coded this sta...

Issue with getting values from child controls in a gridview, to use for the update using a SQLDataSource control
Hi all, I have a gridview bound with a SQLDataSource. I am using the Update feature of the SQLDataSource to update a SQL Server database with values entered into the gridview. However I am not getting it to work. I believe this is due to the controls that contain the user entries are not the gridview itself, but rather child controls within the gridview. I have been using the names of the actual controls but nothing happens. Upon submit, the screen returns blank, and the database is not updated. Here is some code:   <asp:GridView ID="GridEditSettlement" runat="server" AutoGenerate...

How to use the arguments to use() in the package being used
Howdy,=20 The subject says it all believe it or not :) What I'm trying to figure out is how to pass an argument=20 (pragma I believe is the proper term) to use() and do=20 sonethign in the package based on it. I've looked at CGI.pm source but can't seem to track it down.=20 (Similar idea as to CGIs -oldstyle_urls -newstyel_urls) http://search.cpan.org/~lds/CGI.pm-3.04/CGI.pm#PRAGMAS What I'd like to do is something like this: # for old time's sake we'll just use our favorite module use Foo::Monkey qw(:Foo :Bar -doamazingthings); #then in Foo::Monkey...

Using AJAX Issue
Hi Everyone. We have an Web Application that is located on a shared folder on a Server in our network.  2 developers are accessing the same application and they  both have the same computer, the same installation evereything is the same.  The problem is that on one of the computers AJAX control Toolkit does not work at all.  Every time that we try to use it, we get this error message : Server Error in '/Sarde' Application. Security Exception Description: The application attempted to perform an operation not allowed by the security policy.  To gra...

Issue with using StrToDate???
This is a strange error, but for some reason StrToDate is not working correctly. var lastPayrollDate : TDateTime; begin lastPayrollDate := StrToDate('9/30/2020'); //function always returns '12/30/1899' ... end; I am using this function in other places within my application, and it works correctly. I am assuming this is some type of memory leak. Has anyone ever seen this? I have Googled it and cannot find anything. Any ideas on what to do? On 26.04.2010 16:02, Shane Davis wrote: > This is a strange error, but for some reason StrToDat...

An issue when using TBytesStream
When passing the value of a TBytesStream.Bytes to subroutines that rely on checking the Length(...) the size will not be correct unless you reset the size manually first. for example: (Before: Length(YourStream.Bytes) <> YourStream.Size) YourStream.SetSize(YourStream.Size) (After: Length(YourStream.Bytes) = YourStream.Size) I wish the compiler could somehow generate a warning for this. This is probably worth being in the offical documentation too. -- Ray Raymond wrote: > When passing the value of a TBytesStream.Bytes to subroutines > that rely on check...

Issues with using redirection
Hi all, Sorry in advanced if this post belongs in another forum. We have web application that Handles redirections to our websites.  Example: In IIS we have: Site A Site B SiteRedirector So if we want all users to be directed to site A when they try to access site B, SiteRedirector will take the domain of the URL which contains site B (ie. www.B.com/MyStuff/default.aspx) and replace it with Site A's domain (i.e. www.A.com/MyStuff/default.aspx) and does a response.redirect to that new URL.  This works whenever the user tries to access a .aspx page, but would not work if the...

minor sprintf issue
crypt% perl -we 'printf "<%#.6$_>\n", 1 for qw/ b o x /' <0b000001> <000001> <0x000001> crypt% Is it a bug that <%#.6o> does not prepend an extra zero? I notice that on Linux here, the C library does the some, so I guess not. Hugo On Tue, Jul 16, 2002 at 03:20:01PM +0100, Hugo van der Sanden wrote: > crypt% perl -we 'printf "<%#.6$_>\n", 1 for qw/ b o x /' > <0b000001> > <000001> > <0x000001> > crypt% > > Is it a bug that <%#.6o> does not prepend an extra...

Issue in using DPAPI
Friends, I am using DPAPI Encryption using the following syntax to encrypt my credentials aspnet_regiis -pef <section> <Path> After the encryption, when the application is deployed in the web server, I am facing an wierd issue. 1)After 15 mins (or) IIS Reset , I am able to Login immediately, (No Issue) 2) After 15 mins (or) IIS Reset , None of the other users are able to login. Says Login issue with the entered user details (The credentials encrypted was my userID /Password/Domain. And hence Its allowing only me) 3) After I login , rest of the other users are abl...

Web resources about - sprintf issue - embarcadero.cppbuilder.using

Sign in Sign up You are on Mobile because you are using an old version of Internet Explorer. Learn more here Oleg Oshmyan @ chortos Rīga, Latvia ...

F Sharp (programming language) - Wikipedia, the free encyclopedia
F# is a strongly typed functional-first language that uses type inference . Types do not need to be explicitly declared by the programmer; they ...

Volatility Labs
Earlier this month, FireEye researchers Abhishek Singh and Yasir Khalid introduced Trojan Upclicker - malware that detects automated sandboxes ...

在 AIX 应用开发中会遇到进程间通讯的需求,进程间通讯的方法有很多,例如通过共享内存、信号灯、内存映射文件、数据管道、文件、Socket 等等。 在AIX上通过数据管道实现进程间通讯

Wordpress - 虫子窝
从前几天开始,博客上的Gravatar的镜像站被我们伟大的墙给干掉了,好多博客上面的头像都变成了叉叉,开始还以为是我网络的问题,后来经过小黑的提醒,才知道这是伟大城墙的杰作,想不到我们伟大的长城连我们的头像都不放过,佩服,也怪Wordpress的官方,为啥要在3.0版本后的代码里 ...

General Topics Knowledge Articles
ARM technical Support Knowledge Articles for General Topics

Widgets API Documentation — Automattic
This page contains the technical documentation of the WordPress Widgets API (Application Programming Interface). The intended audience for this ...

The Comprehensive List of bash Reference Documentation and Examples
bash versions covered: 4.2 4.1 4.0 3.2.48 3.2 3.1 3.0.16 3.0 2.05 2.04 2.03 2.02.1 2.02 2.01.1 2.01 2.0 1.14.7 readline versions covered: 6.2 ...

Technobrief #11
... localization through the native JavaScript method intended for it (and gracefully degrading if the library is not present). JavaScript sprintf ...

Stunning, Bespoke Works of Art for Residential and Commercial Commissions.
Italian trained I produce High quality Artwork for both commercial & private clients. Paintings, trompe l'oeil work, faux finishes, canvas murals, ...

resources last updated: 11/20/2015 8:18:30 PM