c++ getline sstream bitset lcm预习

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值