【发布时间】:2017-03-20 13:46:29
【问题描述】:
我正在从文件读取到缓冲区,然后我将读取的文本划分为字符串,其中每个文本以新行结尾形成一个新字符串。
这是我的代码:
int ysize = 20000;
char buffer2[ysize];
int flag = 0;
string temp_str;
vector<string> temp;
while(fread(buffer2, ysize, 1, fp2)>0){
//printf("%s", buffer2);
std::string str(buffer2);
//push the data into the vect
std::string::size_type pos = 0;
std::string::size_type prev = 0;
/*means the last read did not read a full sentence*/
if (flag == 1) {
if (buffer[0] == '\n') {
//this means we have read the last senstense correctly, directly go to the next
}
else{
if((pos = str.find("\n", prev)) != std::string::npos){
temp_str+=str.substr(prev, pos - prev);
temp.push_back(temp_str);
prev = pos + 1;
}
while ((pos = str.find("\n", prev)) != std::string::npos)
{
temp.push_back(str.substr(prev, pos - prev));
prev = pos + 1;
}
// To get the last substring (or only, if delimiter is not found)
temp.push_back(str.substr(prev));
if (buffer2[19999] != '\n') {
//we did not finish readind that query
flag = 1;
temp_str = temp.back();
temp.pop_back();
}
else{
flag = 0;
}
}
}
else{
while ((pos = str.find("\n", prev)) != std::string::npos)
{
temp.push_back(str.substr(prev, pos - prev));
prev = pos + 1;
}
// To get the last substring (or only, if delimiter is not found)
temp.push_back(str.substr(prev));
if (buffer2[19999] != '\n') {
//we did not finish readind that query
flag = 1;
temp_str = temp.back();
temp.pop_back();
}
else{
flag = 0;
}}
}
问题是这不能正确读取数据,它几乎消除了一半的文本。
我不确定我在这里缺少什么。我的想法是逐块读取数据,然后逐行分割,这就是while循环中发生的事情。我正在使用标志处理溢出案例。
【问题讨论】:
-
while (std::getline(myFileStream, lineStr)) {...},并相信您的std::ifstream实现会进行合理的缓冲。 -
我做到了,但性能很糟糕。我正在尝试读取数据块以提高性能,当我测试时这是一个显着的差异,但分割字符串有点进退两难
-
我同意 BoBTFish,但也许你可以试试
std::regex或std::stringstream。