C++ 字符串转整数
我们可以通过多种方式将 string
转换为 int
。最简单的方法是使用 C++11 引入的 std::stoi()
函数。
示例 1:使用 stoi() 将 C++ 字符串转换为整数
#include <iostream>
#include <string>
int main() {
std::string str = "123";
int num;
// using stoi() to store the value of str1 to x
num = std::stoi(str);
std::cout << num;
return 0;
}
输出
123
示例 2:使用 atoi() 将字符数组转换为整数
我们可以使用 std::atoi()
函数将 char
数组转换为 int
。atoi()
函数定义在 cstdlib
头文件中。
#include <iostream>
// cstdlib is needed for atoi()
#include <cstdlib>
using namespace std;
int main() {
// declaring and initializing character array
char str[] = "456";
int num = std::atoi(str);
std::cout << "num = " << num;
return 0;
}
输出
num = 456
要了解将字符串转换为整数的其他方法,请访问 将 C++ 字符串转换为整数的不同方法
C++ 整数转字符串
我们可以使用 C++11 的 std::to_string()
函数将 int
转换为 string
。对于旧版本的 C++,我们可以使用 std::stringstream
对象。
示例 3:使用 to_string() 将 C++ 整数转换为字符串
#include <iostream>
#include <string>
using namespace std;
int main() {
int num = 123;
std::string str = to_string(num);
std::cout << str;
return 0;
}
输出
123
示例 4:使用 stringstream 将 C++ 整数转换为字符串
#include <iostream>
#include<string>
#include<sstream> // for using stringstream
using namespace std;
int main() {
int num = 15;
// creating stringstream object ss
std::stringstream ss;
// assigning the value of num to ss
ss << num;
// initializing string variable with the value of ss
// and converting it to string format with str() function
std::string strNum = ss.str();
std::cout << strNum;
return 0;
}
输出
15
有关将字符串转换为浮点数/双精度数的知识,请访问 C++ 字符串转浮点数/双精度数。