C++ 字符串和数字之间的相互转换

能完成字符串和数字转换的方法多种多样:

1.使用string自带函数

数字转字符串:to_string()
字符串转数字:stoi()、stol()、stof()、stod()等等

例:

int i = 42;
string s = to_string(i);
double d = stod(s);

字符串转数字的各个函数还可以选择从字符串的哪个位置开始转换,转换成整型量还可以选择不同的进制,具体见C++primer 328页。

2.使用stringstream

首先要包含sstream头文件,这个类继承自iostream,可以对string进行读写数据。
通过stringstream可以直接完成字符串和数字的互相转换。

例:

//数字转字符串
int num = 12;
string s;
stringstream strs;
strs << num;
strs >> s; //s = “12”
//字符串转数字
string s = "123";
int num;
stringstream strs;
strs << s;
strs >> num; //num = 123

这里的字符串类型不仅可以是string,也可以是char[ ]。当然,C++推荐我们能用string、vector等容器就不要用数组;能用迭代器就不要用普通指针。

3.使用sprintf、sscanf

需要include<stdio.h>

// 数字转字符串
sprintf(str,%d”, num);
// 字符串转数字
sscanf(str,%d”, &rsl);

通过字符串和数字之间的相互转换,我们可以更灵活的处理数据、解决问题,比如下面这个例题:

求1-n范围内包含数字 2、0、1、9 的数字的个数,并计算它们的和。

#include <string>
#include <iostream> 

using namespace std;

int n, num = 0, sum = 0;
string s;
string numbers("2019");
int main()
{
    
    
	cin >> n;
	for (int i = 1; i <= n; ++i)
	{
    
    
		// 将数字转化为string
		s = to_string(i);
		// find_first_of()可以查找numbers中任意一个字符在s中第一次出现的位置
		if (s.find_first_of(numbers) != string::npos) {
    
    
			sum += i;
			++num;
		}
	}
	cout << "1-" << n << "范围内包含2、0、1、9的数字共有" 
	     << num << "个," << "其和为:" << sum << endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43390123/article/details/116094291