【问题标题】:Concatenate integer with string to format string将整数与字符串连接以格式化字符串
【发布时间】:2017-03-09 04:53:14
【问题描述】:

我必须将整数与字符串连接如下,用户将输入一个数字,例如1 它将被放置在这样的字符串中:

std::remove("C:/Users/pcname/Desktop/files/1.txt");

如果用户输入2,就像

std::remove("C:/Users/pcname/Desktop/files/2.txt");

这是非常基本的,但我遇到了这个问题,我尝试使用operator+,但没有奏效。

【问题讨论】:

  • 更具体。展示“不起作用”的有问题的代码。
  • 发帖前请先搜索 StackOverflow。我推荐关键字“stackoverflow c++ concatenate string integer”。

标签: c++


【解决方案1】:

您可以使用std::to_string 将整数转换为std::string,然后使用连接

int file_num = 1;
std::remove("C:/Users/pcname/Desktop/files/" + std::to_string(file_num) + ".txt");

否则会尝试做类似的事情

"C:/Users/pcname/Desktop/files/" + file_num

实际上是在做pointer arithmetic,不会产生你认为会的字符串

【讨论】:

  • [错误] 'to_string' 不是 'std' 的成员
  • 如果你不能使用>C++11,boost::lexical_cast
  • 请详细说明我无法获得您的第二点提升::lexical_cast
  • boost 是您需要包含在项目中的外部库
  • 那是因为你没有使用 C++11 或更高版本。 en.cppreference.com/w/cpp/string/basic_string/to_string
猜你喜欢
  • 1970-01-01
  • 2011-08-16
  • 2022-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-20
  • 2012-07-22
相关资源
最近更新 更多