1、getline
使用c++的cin >> 进行输入也可以输入字符串,但是当 cin 读取数据时,它会传递并忽略任何前导白色空格字符(空格、制表符或换行符)。一旦它接触到第一个非空格字符即开始阅读,当它读取到下一个空白字符时,它将停止读取
#include <iostream>
#include <string>
using namespace std;
int main(){
string str;
cin >> str;
cout << str << endl;
}
遇到有空格的输入时使用getline函数
#include <iostream>
#include <string>
using namespace std;
int main(){
string str;
getline(cin, str);
cout << str << endl;
}
2、sstream
将int类型转换为string类型
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main(){
stringstream ss;
string str;
int i = 5;
ss << i;
ss >> str;
cout << str << endl;
}
将string类型转换为int类型
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main(){
stringstream ss;
string str = "65473";
int i;
ss << str;
ss >> i;
cout << i << endl;
}
把中间带有空格的字符串分开
#include <string>
#include <sstream>
using namespace std;
int main(){
string str= "jkhfa asfd afsd asfd asfd fasd asfd";
stringstream ss(str);
while (ss)
{
string substr;
ss>>substr;
cout << substr << endl;
}
}
3、bitset主要用来处理二进制
#include <iostream>
#include <string>
#include <sstream>
#include <bitset>
using namespace std;
int main(){
//bitset<4> bitset;
bitset<8> bitset1(12);
//cout << bitset << endl; // 0000
cout << bitset1 << endl;// 00001100
}
4.lcm与gcd最小公倍数和最大公约数
#include <iostream>
using namespace std;
int gcd(int a,int b){ //辗转相除法
if(a%b==0) return b;
else return gcd(b,a%b);
}
int lcm(int a,int b){
return a*b/gcd(a,b); //最小公倍数乘最大公约数等于它们的乘积
}
int main(){
int a,b,t;
scanf("%d%d",&a,&b);
if(a<b) {t=a;a=b;b=t;}
t=gcd(a,b);
printf("%d %d",t,a*b/t);
return 0;
}