stringstream与getline的配合
今天在做leetcode题目(#### IP 到 CIDR
)时,需要将IP转化为整形,第一反应就是遍历string,遇到‘.’则截取字符串,然后将字符串转换为十进制;该种方法需要维护截取的字符串个数及截取的起始点。
偶然看到大神采用stringstream与getline的配合,觉得很优秀啊,所以记录一把;
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
class Solution {
public:
void TestStringStream()
{
string ip = "0.0.1.4";
stringstream ss;
ss<<ip;
string rec;
int value = 0;
while (getline(ss, rec, '.')) { // 流,接收字符串,结束符
value = value * 256 + stoi(rec); // 这儿采用stoi函数,注意:atoi函数入参是(char *)
}
cout<<value<<endl;
}
};
int main()
{
Solution sol;
sol.TestStringStream();
return 0;
}
stringstream转换类型(各种类型均可吞入,然后吐出需要的类型)
int Str2Int(string str)
{
int value;
stringstream ss;
ss<<str;
ss>>value;
return value;
}
网友评论