【LeetCode笔记】Compare Version Numbers

    int compareVersion(string version1, string version2) {
        stringstream s1(version1), s2(version2);
        while(1){
            int i1= 0, i2 = 0;
            if(getline(s1, version1, '.'))   //if读取成功,将字符串convert为整型  
                i1 = stoi(version1);         //else读取失败,i1 i2还为0
            if(getline(s2, version2, '.')) 
                i2 = stoi(version2);   
            
            //如果s1 s2同时被读完,说明两字符串相等
            if(!s1 && !s2) //getline()返回值为false:本次读取失败,即上次读取已经extract完了
                return 0;  //getline()返回值为true:本次读取成功,但本次可能已经extract完了
            //不相等的字符串,会在这里给出判断
            if(i1 != i2)
                return i1 > i2 ? 1 : -1;               
        }         
    }

本题解决了对于getline()的几个疑点:

1. getline()作用

(1)
istream& getline (istream& is, string& str, char delim);
(2)
istream& getline (istream& is, string& str);
Get line from stream into string
Extracts characters from is and stores them into str until the delimitation character delim is found (or the newline character, '\n', for (2)).
The extraction also stops if the end of file is reached in is or if some other error occurs during the input operation.
If the delimiter is found, it is extracted and discarded, i.e. it is not stored and the next input operation will begin after it.
Each extracted character is appended to the string as if its member push_back was called.

遇见delim就停止,并discard,下次extract从delim后开始


2.返回值

返回一个istream的引用,可隐式转换为bool型,所以可在while(),if()中使用。当ss被extract完后,ss值还是为true,但如果再次调用getline()去取,ss将为false。



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值