PDA

View Full Version : how can I pass a QString to vsnprintf?



coralbird
18th January 2006, 04:58
QString str("this is a test");
char buffer[1000];
memset(buffer,0,1000);
vsnprintf(buffer,1000-1,"%s",s);

the compiler tells:invalid conversion from 'const char*' to "char*'

In mfc, I can use CString itself or CString.GetBuffer() to do this.

Thanks a lot!

sunil.thaha
18th January 2006, 05:26
Use the ascii() function


vsnprintf(buffer, 1000-1, "%s", s.ascii() );

coralbird
18th January 2006, 06:55
QString.ascii() return const char *,not char *, so if use
vsnprintf(buffer, 1000-1, "%s", s.ascii() )
the compiler report a error: invalid conversion from `const char*' to `char*'

So i have to convert as below,
vsnprintf(buffer, 1000-1, "%s", (char*)s.ascii() )

and there is no error when compiling and linking. but the program
crashed when run to this code .the same happeded when i use latin1().

ChristianEhrlicher
18th January 2006, 07:45
You're using vsnprintf wrong:
http://kernelnewbies.org/documents/kdoc/kernel-api/r889.html

And why don't you use QString::sprintf() (http://doc.trolltech.com/3.3/qstring.html#sprintf)?

coralbird
18th January 2006, 08:12
I have to pass a struct from server to client.every memberof this struct is
a fixed char array.As a part of communication protocol,fixed char array is necessary.
So i must put data into the struct from QString.

yop
18th January 2006, 08:35
I generally use strcpy() for copying a qstring to a char array:

strcpy(buuffer,fooQString.ascii())
You could also pass the QString ascii (or utf8 or whatever) encoded data to a QByteArray and simply memcpy them. The printf family has proven itself pretty unusable for handling QStrings (at least for me)

coralbird
18th January 2006, 09:32
maybe this is a way:
first use QString.sprintf() to format the target,then use strncpy or strcpy to copy it to
destination.

thanks to all!