我被要求更新我的代码,该代码读取文本文件并解析它以获取特定的字符串 .
基本上不是每次都打开文本文件,我想将文本文件读入内存并在对象的持续时间内使用它 .
我想知道是否有类似getline()的函数我可以用于std :: string,就像我可以用于std :: ifstream .
我意识到我可以使用while / for循环,但我很好奇是否还有其他方法 . 这是我目前正在做的事情:
file.txt :( \ n代表换行符)
我的代码:
ifstream file("/tmp/file.txt");
int argIndex = 0;
std::string arg,line,substring,whatIneed1,whatIneed2;
if(file)
{
while(std::getline(file,line))
{
if(line.find("3421",0) != string::npos)
{
std::getline(file,line);
std::getline(file,line);
std::stringstream ss1(line);
std::getline(file,line);
std::stringstream ss2(line);
while( ss1 >> arg)
{
if( argIndex==0)
{
whatIneed1 = arg;
}
argIndex++;
}
argIndex=0;
while( ss2 >> arg)
{
if( argIndex==0)
{
whatIneed2 = arg;
}
argIndex++;
}
argIndex=0;
}
}
}
最后whatIneed1 ==“whatIneed1”和whatIneed2 ==“whatIneed2” .
有没有办法使用像getline()这样的函数将file.txt存储在std :: string而不是std :: ifstream asnd中?我喜欢getline(),因为它使得获取文件的下一行变得更加容易 .
2 回答
如果您已经将数据读入字符串,则可以使用
std::stringstream
将其转换为与getline
兼容的类文件对象 .而不是 grab 一条线然后尝试从中提取一件事,为什么不提取一件事,然后丢弃线?