C/C++:字符串分割、版本比较

一、getline()

1、从屏幕读入,切分,不会跳出while。会一直等待输入,换行无效

string s;
while(getline(cin, s)) {              // 默认按空格切分
    cout << s << endl;
}


string s;
while(getline(cin, s, '.')) {         // 按'.'切分
    cout << s << endl;
}


string s;
while(getline(cin, s, ' .')) {        // 按 空格 和 '.' 切分
    cout << s << endl;
}

2、从屏幕读入一行,切分,会跳出while。

string s;
getline(cin, s);
stringstream sscin(s);

while(getline(sscin, s)) {              // 默认按空格切分
    cout << s << endl;
}


string s;
getline(cin, s);
stringstream sscin(s);

while(getline(sscin, s, '.')) {         // 按'.'切分
    cout << s << endl;
}


string s;
getline(cin, s);
stringstream sscin(s);

while(getline(sscin, s, ' .')) {        // 按 空格 和 '.' 切分
    cout << s << endl;
}

 

二、版本比较

       版本: x.x.x.x,返回最小版本。

#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <climits>
#include <algorithm>
using namespace std;

/*
输入	
	3, 4.3.5.4, 2.10.3, 2.4
最小版本
	2.4
*/

int main()
{
	vector<int> minver(4, INT_MAX);    //最小版本号初始化
	int len = 0;                       //最小版本号长度 0<=len<=4

	//将cin读到另一个流scin中,否则while跳不出去
	string s;
	getline(cin, s);
	stringstream scin(s);	
	
	//版本号比较
	while(getline(scin, s, ',')) {             //按版本号切分
		
		//cout << "#" << s << "#" << endl;
		vector<int> temp(4, 0);
		int k = 0;
		stringstream sv(s);
		
		while(getline(sv, s, '.')) {           //按数字切分
			
			//cout << "@" << s << "@" << endl;
			stringstream sn(s);
			int x;
			sn >> x;
			temp[k++] = x;
			//cout << "&" << x << "&" << endl;
		}
		
		for(int i=0; i<4; i++) {               //比较
			if(temp[i] < minver[i]) { 
				minver = temp;
				len = k;
				break;
			}
		}
	}
	
	//输出最小版本号
	for(int i=0; i<len-1; i++)
	{
		cout << minver[i] << '.';
	}
	cout << minver[len-1];
	
	getchar();
	return 0;
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值