在 C++ 中使用 to_string 将 Int 转换为 String
当你在代码中处理字符串时,你可能想执行某些操作,比如将两个字符串连接起来(或连在一起)。
但在有些情况下,你希望把数值当作字符串来处理,因为把字符串和整数连接起来会出错。
在这篇文章中,我们将看到如何使用 C++ 中的 to_string()
方法将一个整数转换为字符串。
如何用 to_string() 转换整数
为了使用 to_string()
方法,我们必须将整数作为参数传入。下面是语法的内容,以帮助你理解:
to_string(INTEGER)
让我们看一个例子。
#include <iostream>
using namespace std;
int main() {
string first_name = "John";
int age = 80;
cout << first_name + " is " + age + " years old";
}
从上面的代码中,你会期望在控制台中看到 “John is 80 years old”。但这实际上会返回一个错误,因为我们正试图用一个整数来连接字符串。
让我们使用 to_string()
方法来解决这个问题。
#include <iostream>
using namespace std;
int main() {
string first_name = "John";
int age = 80;
string AGE_TO_STRING = to_string(age);
cout << first_name + " is " + AGE_TO_STRING + " years old";
}
我们创建了一个名为 AGE_TO_STRING
的新变量,在 to_string()
方法的帮助下存储了 age
变量的字符串值。
正如你在例子中看到的,整数的 age
被作为参数传入到 to_string()
方法中,转换为字符串。
现在,当我们运行这段代码时,我们将 “John is 80 years old” 打印到控制台。
to_string()
方法在我们想将 float
和 double
数据类型的值——用于存储带小数的数字——转换为字符串时也能发挥作用。
下面是一些例子:
#include <iostream>
using namespace std;
int main() {
string first_name = "John";
float age = 10.5;
string AGE_TO_STRING = to_string(age);
cout << first_name + " is " + AGE_TO_STRING + " years old";
// John is 10.500000 years old
}
上面的例子显示了一个 float
值被转换为一个字符串。在输出中(上面代码中的注释),你可以看到字符串中的小数值。
对于 double
数据类型:
#include <iostream>
using namespace std;
int main() {
string first_name = "John";
double age = 10.5;
string AGE_TO_STRING = to_string(age);
cout << first_name + " is " + AGE_TO_STRING + " years old";
// John is 10.500000 years old
}
这与上一个例子的结果相同。唯一不同的是,我们使用的是一个 double
值。
总结
在这篇文章中,我们谈到了在 C++ 中使用 to_string()
方法将一个整数转换成一个字符串。
在例子中,我们试图将字符串和一个整数串联成一个较大的字符串,但这给了我们报错了。
使用 to_string()
方法,我们能够转换 int
、float
和 double
数据类型的变量,并把它们当作字符串来使用。