Conversion between C++ strings and numbers

There are many ways to accomplish string and number conversion:

1. Use string’s own functions

Number to string: to_string()
String to number: stoi(), stol(), stof(), stod(), etc.

example:

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

Each function that converts a string to a number can also choose which position in the string to start converting from, and you can also choose different bases when converting to an integer. For details, see page 328 of C++primer.

2. Use stringstream

First, you must include the sstream header file. This class inherits from iostream and can read and write string data.
Through stringstream, you can directly convert strings and numbers to each other.

example:

//数字转字符串
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

The string type here can be not only string, but also char[]. Of course, C++ recommends that we don’t use arrays if we can use containers such as strings and vectors; we don’t use ordinary pointers if we can use iterators.

3. Use sprintf, sscanf

Requires include<stdio.h>

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

Through the mutual conversion between strings and numbers, we can process data and solve problems more flexibly, such as the following example:

Find the number of numbers in the range 1-n that contain the numbers 2, 0, 1, and 9, and calculate their sum.

#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;
}

Guess you like

Origin blog.csdn.net/weixin_43390123/article/details/116094291