读书人

std:string 中有相仿sscanf的处理函数

发布时间: 2013-01-07 10:02:25 作者: rapoo

std:string 中有类似sscanf的处理函数吗?
直接使用字符串函数中的sscanf取各个字段习惯了,现在转用std:string感觉用起来总不舒服.....
std中有没有类似的函数可以使用呢?
[解决办法]
stringstream
[解决办法]
#include <iostream>
#include <sstream>
using namespace std;

int main()
{
std::string str = "abc efg";
string buf1, buf2;
int index = str.find(" ");
for(int i = 0; i < str.size(); i++)
{
if( i < index )
{
buf1 += str[i];
}else if( i == index)
{
continue;
}else
{
buf2 += str[i];
}
}
cout << buf1 << endl;
cout << buf2 << endl;
}


sstream.h 中有sstringstream和istringstream,应该能解决你的问题,但是由于本人也不擅长用这二个函数,觉得很麻烦,没有sscanf和sprintf用着方便,所以也不太用过。其实C++完全兼容C,所以我觉得用sscanf和sprintf没有什么不可,不用刻意追求C++,举个例子来说吧,有几个C++程序员去用C++那几个强转的函数呢?
[解决办法]


#include <iostream>
#include <sstream>

int main()
{
std::string str="abc efg";
std::string Buf1,Buf2;
std::stringstream s(str);
s >> Buf1 >> Buf2;
}

[解决办法]
boost有

读书人网 >C++

热点推荐