문제

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 following 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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top