C++中常用的函数总结

版权声明:如若转载,请联系作者。 https://blog.csdn.net/liu16659/article/details/86775466

C++中常用的函数总结

1.字符串转数字函数

字符串转数字是编程中常见的需求,自己手写这个需求倒不是很难,但是如果有直接可以调用的库则是十分便捷的。为此,C++标准库提供了一系列的字符串转数字 的函数。常用的如下:

1.1stoi()函数
  • 这里的stoi意思即是string to int,简写下来就是stoi()函数。
  • 简单示例
#include<cstdio>
#include<cstring>
#include<iostream>

using namespace std;

int main(){
	string a = "2";	
	int a1 = stoi(a);	
	cout << "a1 = "<< a1 <<"\n";	
}
  • 执行结果
    在这里插入图片描述
1.2 stod()函数
  • string to double
  • 简单示例
#include<cstdio>
#include<cstring>
#include<iostream>

using namespace std;

int main(){
	string b = "2.3";
	double b1 = stod(b); 	
	cout << "b1 = "<< b1 << "\n"; 	
}
  • 执行结果
    在这里插入图片描述

2.字符串操作函数

2.1substr()函数
  • 用处
    用于截取部分字符串。

  • 简单示例

#include<cstdio>
#include<cstring>
#include<iostream>

using namespace std;

int main(){	
	string source = "hello world";
	
	//substr(a,b)截取 [a,b) 字符串 
	string sub = source.substr(0,1); 
	cout << "sub = "<< sub<<"\n"; 
}
  • 执行结果
    在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/liu16659/article/details/86775466