【问题标题】:How do I append an integer to a string? [duplicate]如何将整数附加到字符串? [复制]
【发布时间】:2016-02-11 16:23:54
【问题描述】:

这是对my question yesterday的跟进。

我正在使用一个函数来下载文件:

void downloadFile(const char* url, const char* fname, const char* id ) {
  //..
}

这被称为:

downloadFile("http://servera.com/file.txt", "/user/tmp/file.txt", "/home/user/Download/xxxx");

如图所示,这适用于固定的 id,但我需要将 xxxx 替换为随机数:

srand(time(NULL));
int rdn = rand();

如果我尝试:

downloadFile("http://servera.com/file.txt", "/user/tmp/file.txt", "/home/user/Download/" + rdn);

我明白了

error: invalid conversion from ‘int’ to ‘const char*’ [-fpermissive]

那么如何将rdn 附加到字符串"/home/user/Download/" 中呢?比如rdm == 123456789,我想把"/home/user/Download/123456789"传给函数。

【问题讨论】:

  • sprintf,但使用std::string / std::to_string
  • 您希望通过"/home/user/Download/" + rdn实现什么目标???
  • 我对不赞成票特别是接近票感到非常困惑。对我来说,这似乎是一个程序员,他的背景是你可以使用+ 将事物连接到一个字符串,例如在 Java 中。 @barakmanos 我很确定他正在尝试将数字(作为字符串)连接到前缀。
  • @Rocket 如您所见,您的意图对每个人来说都不是很清楚。因此,即使您的问题具有一些非常好的属性,例如相关代码 sn-ps 和您看到的错误,但由于无法弄清楚您的意图,人们还是相当不屑一顾。我建议在这个问题和将来更清楚地说明这一点。
  • 感谢@Rocket 的编辑。不幸的是,许多 SO 用户对不是 100% 符合规范的问题非常不耐烦。在他们的辩护中,大多数关于我们对问题的期望的规则都是经过深思熟虑、尝试和证明的。但是,对于具有 PHP 背景的人来说,您破坏代码的意图可能非常明显,所以我理解您为什么不包含它。重点是,不要因为以后发帖而气馁。

标签: c++ random char int


【解决方案1】:

正如@leemes 所说,您可以使用 sprintf:

char str[100];
sprintf(str,"/home/user/Download/%d",rdn);
downloadFile("http://servera.com/file.txt", "/user/tmp/file.txt", str);

【讨论】:

  • 这里最好使用snprintf() 而不是常规的sprintf()
  • 为了~~对所有神圣事物的爱~~对鼻恶魔的仇恨,请始终使用snprintf
  • 你能解释一下 snprintf 和 sprintf 之间的区别吗?为什么要担心使用一个而不是另一个?你如何使用 snprintf ?这个解决方案对我很有效!
  • 字符串函数(包括 sprintf、strcmp、strcpy、...)有一个 size limit 版本。例如 snprintf 确保生成的字符串的大小不超过指定的大小。其用法如下:snprintf(str,99,"/home/user/Download/%d",rdn);它的偏好是由于其受控(和预测!)的行为:)
【解决方案2】:

如果你使用 c++ 11 你可以这样做

std::string download_location = "/home/user/Download/" + std::to_string(rdn)
downloadFile("http://servera.com/file.txt", "/user/tmp/file.txt", download_location.c_str());

更好的办法是取消 char* 并在任何地方使用字符串。 char* 太容易引入错误了。

或者,您也可以使用 stringstream 进行通用且高效的字符串连接/格式化。

#include <sstream>
...

stringstream download_location_stream;
download_location_stream << "/home/user/Download" << rdn;

downloadFile("http://servera.com/file.txt", "/user/tmp/file.txt",
             download_location_stream.str().c_str());

【讨论】:

  • 当我尝试这个时,我得到错误 to_string not in std。
  • 如果你做了很多字符串连接,你可能需要考虑重载operator+来帮助你。 /** append a string with a string-ified T */ template&lt;typename T&gt; std::string operator+(const std::string &amp;a, const T &amp;b) { return a + std::to_string(b); } /*** prepend a string with a string-ified T */ template&lt;typename T&gt; std::string operator+(const T &amp;a, const std::string &amp;b) { return std::to_string(a) + b; } 然后std::string("/some/dir/")+rnd 应该可以工作。 (抱歉格式错误。无法回答已关闭的问题。)
  • @Rocket 您可能不使用 C++11 编译器或禁用某些相关功能。没关系,我添加了另一种适用于旧编译器的方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-14
  • 2017-11-11
  • 2012-01-12
  • 1970-01-01
  • 2010-09-09
  • 1970-01-01
相关资源
最近更新 更多