【问题标题】:How do I insert a value into a URL?如何在 URL 中插入值?
【发布时间】:2010-07-30 09:49:07
【问题描述】:

我有以下代码,我尝试将 randomValue 插入 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"));

报如下错误:

错误:“const char*”和“const char [18]”类型的无效操作数转换为二进制“operator+”

所以,我想将randomValue 附加到 URL 中。我该怎么做?

【问题讨论】:

    标签: c++ qt qstring


    【解决方案1】:

    为此使用 QString。它比 std::string 功能强大得多,它直接提供你需要的东西。

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

    更多详情请见QString documentation

    【讨论】:

    • 是的,我喜欢将参数传递给字符串的 qt 方式。
    【解决方案2】:

    char* 没有 operator +。您应该使用 C++ 风格的 std::string,或者 qt 特定的 QString,它们都支持 operator +

    其实QString 是个好主意,因为QUrl 在构造函数中接受它。

    【讨论】:

      【解决方案3】:

      使用sprintf 函数。例如,请参阅here

      另一种选择是使用 std::string 甚至 std::ostringstream 。取决于你喜欢什么(我不知道 QUrl 可以接受什么样的参数)。

      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 );
      

      注意%d 你想要你的价值的地方。这使得sprintf 将其替换为randomValue 的值,作为第二个参数传递。有关详细信息,请参阅上面的参考链接。

      注意:您可能会考虑按照另一个答案中所述的 Qt 方式进行操作。

      【讨论】:

      • 我打印变量 randomValue 但如何附加到 url 代码中,我的意思是我使用 + 运算符附加但它不被接受。那么哪个运营商接受了?
      【解决方案4】:

      使用 stringstream 构建字符串

      std::ostringstream oss; oss http://blogsearch.google.com/blogsearch?q=C&start=" 加载(QUrl(oss.str()));

      【讨论】:

        【解决方案5】:

        使用

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

        它应该可以工作。

        C++(或 QString)都不会隐式地将数字转换为字符串。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2023-03-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-03-24
          • 1970-01-01
          相关资源
          最近更新 更多