开发者

How do I insert a value into a URL?

I have the following code where I try to insert randomValue into an URL.

int randomValue = qrand() % 100;
view = new QWebView(this) ;

view->load(QUrl("http://blogsearch.google.com/blogsearch?q=C&start="+randomValue+"&num=1&output=rss"));

The followi开发者_如何学Gong error is reported:

error: invalid operands of types 'const char*' and 'const char [18]' to binary 'operator+'

So, I want to append the randomValue into the URL. How do I do it?


Use QString for this. It is far more capable than std::string and it provides what you need directly.

QString baseurl("http://blogsearch.google.com/blogsearch?q=C&num=1&output=rss&start=%1");
view->load(QUrl(baseurl.arg(randomValue)));

See QString documentation for more details.


There is no operator + for char*. You should either use C++-style std::string, or qt-specific QString, both of them support operator +.

Actually, QString is a good idea, because QUrl accepts it in the constructor.


Use the sprintf function. See here for example.

Another option would be to use std::string or even std::ostringstream . Depends on what you prefer (and I do not know what kind of params can QUrl take).

char mytext[ 256 ]; // make sure the buffer is large enough!
int randomValue = 12345;
sprintf( "http://blogsearch.google.com/blogsearch?q=C&start=%d&num=1&output=rss", randomValue );

Notice the %d where you want your value. This makes sprintf to replace it with the value of randomValue, passes as a second parameter. For more info, please see the reference link above.

NOTE: you might consider to do it the Qt way as described in another answer.


Use stringstream to build the string

std::ostringstream oss; oss << "http://blogsearch.google.com/blogsearch?q=C&start=" << randomValue << "&num=1&output=rss"; view->load(QUrl(oss.str()));


use

... + QString::number( randomValue ) + ...

and it should work.

Neither C++ (nor QString) implicitely convert numbers to strings.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜