如何在 C++ 中向字符串添加整数
    
    Jinku Hu
    2023年10月12日
    
    C++
    C++ String
    
 
本文将讲解几种在 C++ 中向字符串添加整数的方法。
使用+= 运算符和 std::to_string 函数将整型添加到字符串中
    
std::string 类支持使用+ 和+= 等核心运算符进行最常见的连接形式。在下面的例子中,我们演示了后一种,因为它是最佳解决方案。在将 int 值追加到字符串的末尾之前,应该将 int 值转换为相同的类型,这可以通过 std::to_string 函数调用来实现。
#include <iostream>
#include <string>
#include <vector>
using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::to_string;
int main() {
  string app_str = "This string will be appended to ";
  int number = 12345;
  cout << app_str << endl;
  app_str += to_string(number);
  cout << app_str << endl;
  return EXIT_SUCCESS;
}
输出:
This string will be appended to
This string will be appended to 12345
上述方法也与浮点数兼容,如下面的代码示例所示。
#include <iostream>
#include <string>
#include <vector>
using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::to_string;
int main() {
  string app_str = "This string will be appended to ";
  float fnumber = 12.345;
  cout << app_str << endl;
  app_str += to_string(fnumber);
  cout << app_str << endl;
  return EXIT_SUCCESS;
}
输出:
This string will be appended to
This string will be appended to 12.345000
使用 std::stringstream 将整型添加到字符串中
stringstream 可以将多种输入类型并以字符串格式存储。它提供了易于使用的操作符和内置的方法来将构建的字符串重定向到控制台输出。
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::stringstream;
using std::to_string;
int main() {
  string app_str = "This string will be appended to ";
  int number = 12345;
  stringstream tmp_stream;
  cout << app_str << endl;
  tmp_stream << app_str << number;
  cout << tmp_stream.str() << endl;
  return EXIT_SUCCESS;
}
输出:
This string will be appended to
This string will be appended to 12345
使用 append() 方法将整型添加到字符串中
append() 是 std::basic_string 类的一个成员函数,它可以根据参数的指定进行多种类型的追加操作。在最简单的形式下,当传递一个字符串参数时,它将追加到调用该方法的对象上。作为另一种形式,它可以接受一个单一的字符和整数,代表给定字符的追加计数。我们可以在手册中看到完整的参数列表。
#include <iostream>
#include <string>
#include <vector>
using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::to_string;
int main() {
  string app_str = "This string will be appended to ";
  int number = 12345;
  cout << app_str << endl;
  app_str.append(to_string(number));
  cout << app_str;
  return EXIT_SUCCESS;
}
输出:
This string will be appended to
This string will be appended to 12345
        Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
    
作者: Jinku Hu
    
