要把文件的字符串读出,并将它分块(split)。
首先文件一行一行读台麻烦,网上搜了下,发现宝贝,一次读取整个文件到内存中, http://www.360doc.com/content/13/1101/01/14458144_325725835.shtml
std::ifstream inf("hlh_lc_cluster.def",std::ios::in);
if(!inf)
{
std::cout<<"cannot open file"<<std::endl;
return -1;
}
std::string str_file="";
std::stringstream tmp;
tmp<<inf.rdbuf();
str_file=tmp.str();
很多其他语言的libary都会有去除string类的首尾空格的库函数,但是标准C++的库却不提供这个功能。
同样,网上搜了一个代码,调试的时候发现分出来的结果一个想要的结果,接着一个空元素,…… 仔细查看了下代码,原来他将delim长度默认成了1,没考虑到分词符可能是多个字符。
//注意:当字符串为空时,也会返回一个空字符串
void split(std::string& s, std::string& delim,std::vector< std::string >* ret)
{
size_t last = 0;
size_t index=s.find_first_of(delim,last);
while (index!=std::string::npos)
{
ret->push_back(s.substr(last,index-last));
last=index+1;
index=s.find_first_of(delim,last);
}
if (index-last>0)
{
ret->push_back(s.substr(last,index-last));
}
}
修改代码:将last=index+1; 改成last=index+delim.length();
OK!
ps: 之前误以为find_first_of是找第一个匹配的位置,今天做另一个东西的时候突然发现程序有问题,追查之下才发现find_first_of不是之前理解的意思。
首先,STL string 中有find函数和find_first_of函数,find函数(str1.find(str2))才是找str1中有str2子串,如果有则返回第一个匹配子串的首字符的index,如果没有则返回string::npos; 而find_first_of 函数(str1.find_first_of(str2))是找str1中出现str2字符,如果有……
修改代码: 将find_first_of 换成find
参见 另一篇博文http://blog.youkuaiyun.com/jinjiaoooo/article/details/26626117